java中的重复引用变量

时间:2016-06-10 16:27:12

标签: java

我有一个带有main方法的2个java类和一个带有私有变量的类。获取和设置的方法。所以,我的问题是我们可以在所有setter(3 setter)中使用相同的对象引用变量,并在所有getter(3)中使用不同的引用变量吗? 我用过那个,我得到了空值。

但是,当我使用3个不同的对象引用变量为3个getter和相同的3个对象引用变量for getters然后它工作正常。 那么,有人能解释我这个概念吗?

package project1;

public class 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?
}

}

1 个答案:

答案 0 :(得分:0)

您获得空值的原因是您没有为第二种情况设置这些变量的值。例如,让我们执行以下操作:

    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