关于 Java 中的 Object/Class 个实例
Regarding Object/Class Instances in Java
考虑以下场景:
public class ClassA {
private Main main;
Object obj = new Object;
public void setMain(Main main) {
this.main = main;
}
methodA() { //called first
obj.someFunction();
main.someFunction();
}
methodB() { //called second
obj.someOtherFunction();
}
}
方法 B 会使用与方法 A 相同的 "obj" 实例吗?如果不是,如何修改代码使其成为这样?
对于这样一个基本的问题,我深表歉意,但这是一个我从开始学习java以来一直不清楚的概念,即使在网上搜索了无数次。
是的。
Java不会在你背后改变对象
是的。
如果您想将其可视化,您可以打印对象以查看该散列:
public class ClassA {
private Main main;
Object obj = new Object;
public void setMain(Main main) {
this.main = main;
}
methodA() { //called first
System.out.println(obj); //you should see the same hash as in methodB
obj.someFunction();
main.someFunction();
}
methodB() { //called second
System.out.println(obj); //you should see the same hash as in methodA
obj.someOtherFunction();
}
}
如果你的测试用例是:
ClassA objectA = new ClassA(new Main());
objectA.methodA();
objectA.methodB();
在调用 methodA()
和 methodB()
之间没有任何东西会改变 obj
实例变量的值,然后是的,它们都将使用相同的 obj
实例.
考虑以下场景:
public class ClassA {
private Main main;
Object obj = new Object;
public void setMain(Main main) {
this.main = main;
}
methodA() { //called first
obj.someFunction();
main.someFunction();
}
methodB() { //called second
obj.someOtherFunction();
}
}
方法 B 会使用与方法 A 相同的 "obj" 实例吗?如果不是,如何修改代码使其成为这样?
对于这样一个基本的问题,我深表歉意,但这是一个我从开始学习java以来一直不清楚的概念,即使在网上搜索了无数次。
是的。
Java不会在你背后改变对象
是的。
如果您想将其可视化,您可以打印对象以查看该散列:
public class ClassA {
private Main main;
Object obj = new Object;
public void setMain(Main main) {
this.main = main;
}
methodA() { //called first
System.out.println(obj); //you should see the same hash as in methodB
obj.someFunction();
main.someFunction();
}
methodB() { //called second
System.out.println(obj); //you should see the same hash as in methodA
obj.someOtherFunction();
}
}
如果你的测试用例是:
ClassA objectA = new ClassA(new Main());
objectA.methodA();
objectA.methodB();
在调用 methodA()
和 methodB()
之间没有任何东西会改变 obj
实例变量的值,然后是的,它们都将使用相同的 obj
实例.