Reputation: 85
I am trying to understand how object interactions are programmed.
I think I understand the basic principle that an object has methods that have access to its data and can change it. But what if two objects interact and something object1 does has to change the state of object2.
Say you have a Person object and a Ball object and the Person has to kick the ball, thus changing the coordinates of the ball.
Would it look something like:
person.kick(ball)
where person.kick looks like
kick(whatToKick) {
whatToKick.changeCoord();
}
Is this at all correct?
Should an objects state only be changed by its own methods?
Is the pattern for object interaction always:
Also if anybody could recommend a book on OOP principles and design patterns that would be very nice.
Thanks.
Upvotes: 0
Views: 204
Reputation: 8215
Basically, what you wrote is correct:
The state of an object should only be modified by that object's methods. Otherwise you would have to make the state public and lose encapsulation.
If object A needs to call a method of object B, it needs a reference of B. How else should the method be called.
But what's more important: You seem to assume that OOP is all about modifying objects' state. Unfortunately this impression is given by many introductions. But it is not true. Mutable state causes lots of issues, making programs harder to read and to test. Fortunately most of what you probably need can be done with immutable objects. Just google for immutability. I also recommend to have a look at functional programming where immutability is standard.
(I won't answer your last question because it is off-topic here.)
Upvotes: 2