java - java中的重复引用变量

标签 java

我有 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,因为您还没有给它们赋值。因此,obj2obj3 的变量尚未实例化,调用它们将返回 null

关于java - java中的重复引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37753057/

相关文章:

java - 如何在 native c++ jni中实现java类型数组

java - 如何从接口(interface)数组列表中获取某个对象

java - 如何读取大文本文件并在 Java 中使用它

java - react 链中 next() 的奇怪行为

java - 需要有关使用 java 发送短信的帮助

java - 在IntelliJ IDEA中导入Springframework源代码

java - 第一个字母的样式

Java复制没有双引号的整个文件

java - 将内容流式传输到 JSF UI

java - 如何在两台计算机之间传递大量数据