有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

仍在努力理解Java中的面向对象编程

假设有一个名为Hello的类,我如何将名为var1和var2的变量声明为类Hello中对象的引用? 我以为只是你好,var1,var2

另外,如果只使用默认构造函数构造类Hello的对象的实例,那么它就是Hello Hello=new Hello()

最后,我的最后一个问题是,如果我要使用默认构造函数实例化Hello类的一个对象,并将该对象分配给名为var1的varaible,那么它就是Hello var1=new Hellow();。如何将对名为var1的对象的引用分配给名为var2的变量

我知道有一个术语来描述变量var1和var2的当前状态,但我想不起来


共 (1) 个答案

  1. # 1 楼答案

    只是给出了一个测试例子来说明这些事情

    public class Hello {
        Hello var1, var2;
        public static void main(String[] args){
            Hello h1 = new Hello();
            h1.var1 = h1;
            System.out.println("h1.var1    "+ h1.var1);
    
            Hello h2 = new Hello();
            h1.var2 = h2;
            System.out.println("h1.var2    "+ h1.var2);
    
            h1.var2 = h1.var1;
    
            System.out.println("h1.var1    "+ h1.var1);
            System.out.println("h1.var2    "+ h1.var2);
        }
    }
    
    
        Output :- 
    
        h1.var1    Hello@19e0bfd
        h1.var2    Hello@139a55
        h1.var1    Hello@19e0bfd
        h1.var2    Hello@19e0bfd
    

    Assuming there is a class named Hello, How would I declare variables named var1 and var2 to be references to objects in the class Hello? I assumed it would just be Hello var1, var2;

    您可以看到,有两个声明为同一类的变量可以引用Hello类实例

    Also to just construct an instance of the object of the class Hello using the default constructor would it just be Hello hello = new Hello();

    是的,每个类都有默认的构造函数,所以你可以像这样初始化类

    Finally my last question is if I were to instantiate an object of the class Hello using the default constructor and assign that object to the varaible named var1 it would just be Hello var1 = new Hellow();. How would I assign the reference to the object named var1 to the variable named var2

    正如您看到的输出,var2的哈希代码与h1.var2 = h1.var1语句之后的var1相同。这表明var2之前的引用被var1引用替换。所以这里不复制对象,而是复制对对象的引用。检查{}和{}的相同{}

    就这样