我有 2 个 java 类,一个带有 main 方法,一个带有私有(private)变量和用于获取和设置的方法。所以,我的问题是我们可以在所有 setter(3 个 setter)中使用相同的对象引用变量,并在所有 getters(3)中使用不同的引用变量吗? 我使用了它,但得到了空值。
但是,当我为 3 个 getters 使用 3 个不同的对象引用变量,并为 getters 使用相同的相应 3 个对象引用变量时,它就可以正常工作了。 那么,有人能给我解释一下这个概念吗?
打包项目1;
公共(public)类Encapsulationjerry1 {
public static void main(String[] args)
{
System.out.println("Now, we are gonna test our Encapsulation");
// I gave different variables for all setters and same respective variables for getters. This is working fine.
Encapsulationtom1 obj1 = new Encapsulationtom1();
Encapsulationtom1 obj2 = new Encapsulationtom1();
Encapsulationtom1 obj3 = new Encapsulationtom1();
obj1.setDesignation("Lead Designer");
obj2.setEmployeeId(23452);
obj3.setEmployeeName("Meliodas");
System.out.println("The designation is "+ obj1.getDesignation());
System.out.println("The Employee Id is "+ obj2.getEmployeeId());
System.out.println("The Employee Name is "+ obj3.getEmployeeName());
// But when i give same variable to all setters and a different variable to all getters, it gave me null value. WHY?
}
}
最佳答案
您获得空值的原因是您尚未为第二种情况设置这些变量的值。例如,让您执行以下操作:
Encapsulationtom1 obj1 = new Encapsulationtom1();
Encapsulationtom1 obj2 = new Encapsulationtom1();
Encapsulationtom1 obj3 = new Encapsulationtom1();
obj1.setDesignation("Lead Designer");
obj1.setEmployeeId(23452);
obj1.setEmployeeName("Meliodas");
System.out.println("The designation is "+ obj1.getDesignation());
System.out.println("The designation is "+ obj2.getEmployeeId());
System.out.println("The designation is "+ obj3.getEmployeeName());
这两行:
System.out.println("The designation is "+ obj2.getEmployeeId());
System.out.println("The designation is "+ obj3.getEmployeeName());
将返回Null
,因为您还没有给它们赋值。因此,obj2
和 obj3
的变量尚未实例化,调用它们将返回 null
。
关于java - java中的重复引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37753057/