how objects interacts with each other in java using methods?
13,770
Objects typically talk to one another via use of references. For example:
class Robot {
private String m_name;
public void SetName(String name) {
m_name = name;
}
public String GetName() {
return m_name;
}
public void TalkTo(Robot robot, String speech){
console.writeline(robot.GetName + " says " + speech " to you.");
}
}
void MyMethod() {
Robot robotOne = new Robot(); // variable robotOne contains a reference to a robot
Robot robotTwo = new Robot(); // variable robotTwo contains a reference to another robot
robotTwo.SetName("Robert");
// the first robot says hi to the second
robotOne.TalkTo(robotTwo, "hello");
// output
// Robert says hello to you
}
Comments
-
dganesh2002 almost 2 years
I am learning java and can do pretty much coding myself without any issues. But I have been always reading in the books - In java, objects interact with each other by invoking methods of other objects?
I am unsure if I got that clearly. Example is like, a
Robot
class which has methods likemoveForward()
,comeToBase()
,increaseSpeed()
etc. Now if there are two robot objects, then how will they interact with each other to avoid clash? I can understand very well that each robot object can invoke its own methods independently and run independently but how does the interaction between the object happens? Can someone explain based on the above example?