【问题标题】:Duplicate reference variable in javajava中的重复引用变量
【发布时间】:2016-06-10 16:27:11
【问题描述】:

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

但是,当我为 3 个 getter 使用 3 个不同的对象引用变量并为 getter 使用相同的相应 3 个对象引用变量时,它工作正常。 那么,有人可以解释一下这个概念吗?

打包项目1;

公共类封装jerry1 {

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

}

【问题讨论】:

标签: java


【解决方案1】:

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

    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

【讨论】:

  • 好的,我想我明白了:D 用于设置值的相同对象可用于获取值:D
  • 是的!如果你没有在对象中设置值,你将无法获取它,它只会返回null
  • 好的,谢谢您的帮助。我只是暂时没有连接这些东西,但现在一切都完美了:D
  • 太好了!不要忘记投票和accept
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-26
  • 2013-04-24
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
相关资源
最近更新 更多