objects with state and behavior in oop

点点圈 提交于 2019-12-03 09:40:23

问题


I keep hearing the term object has behavior and state or just one of them. But what is the difference or what does it mean, and if anyone can give an example I would really appreciate it.


回答1:


  • Lamp is an object.
  • The "state" in lamp:on and off.
  • The "behavior" in lamp:turn on and turn off.

In programming you declare states in "fields" and behaviors in "methods" etc..

Read and learn object-oriented.




回答2:


class Door {
  boolean isOpen;

  void close(){
    isOpen = false;
  }
}

Look at this simple snippet. We have class Door, it has a state isOpen - variable describes current state of this door. Method close it is behaviour of door, when we call it, we change current state of object.

I advice you to read good for beginners book about object oriented programming: Head First Object-Oriented Analysis and Design. If you read it you get better understanding.




回答3:


abstract class Animal
{
   int age;
   abstract void Run();
}

class Tiger:Animal
{
    override void Run()
    {
      //something.
    }
}

main()
{
     Tiger t1 = new Tiger();
     Tiger t2 = new Tiger();
     t1.age = 25;
     t2.age = 10;
}

Now you have created two Tiger objects. Tiger can Run. That is the behavior of the object Tiger. t1 age is 25 and t2 age is 10. t1.age, t2.age is the state of the object.

Hope this helps.




回答4:


Objects are defined by methods and fields.

fields or state can be thought of current conditions within an object. A banana's state would be its shape and colour and size Methods or behaviours can be thought of its acting. With the banana, whether it is ripe or dry can be the behaviour.



来源:https://stackoverflow.com/questions/9967733/objects-with-state-and-behavior-in-oop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!