dga*_*002 4 java methods interaction object
我正在学习java,并且可以自己完成很多编码,没有任何问题。但我一直在书上读 - 在java中,对象通过调用其他对象的方法来相互交互?
我不确定我是否清楚地理解了这一点。例子就像,一个Robot具有moveForward()、等方法的类comeToBase()。increaseSpeed()现在如果有两个机器人对象,那么它们将如何相互作用以避免冲突?我很理解每个机器人对象都可以独立调用自己的方法并独立运行,但是对象之间的交互是如何发生的呢?有人可以根据上面的例子解释一下吗?
对象通常通过使用引用来相互通信。例如:
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
}
Run Code Online (Sandbox Code Playgroud)