【发布时间】:2018-08-23 11:26:40
【问题描述】:
这可能是非常新手,但我已经尝试了一段时间,但我无法找到答案。
package playground.space;
public class Fourlegs {
String room;
public static void main(String[] args) {
Fourlegs program = new Fourlegs();
program.start();
}
public void start() {
Fourlegs cat = new Fourlegs();
cat.room = "office";
Fourlegs dog = new Fourlegs();
dog.room = "office";
//dog moves to the carpark, and the cat follows the dog
dog.move("carpark");
}
public void move(String i) {
this.room = i;
//cat cannot be resolved to a variable
cat.room = this.room; //the cat's room will be the same as the dog's room.
System.out.println("the cat is in the " + cat.room);
}
}
我收到错误:cat 无法解析为变量。(显然)。
如何通过其他方法操作“猫”?
【问题讨论】:
-
cat在方法start()中声明,这意味着它仅在该方法的范围内可用。将其声明为类属性(如room),您可以在该类的所有方法中使用它。 -
为什么在
dog上调用move也会影响cat? -
了解一点 Java 中的对象引用可能会有所帮助。这是 StackOverflow 上的一篇文章,我对此进行了解释:Two newly created objects seem to refer to the same address.