首页 > 解决方案 > 每次实例化子类时都会创建超类对象吗?

问题描述

这是一个两部分的问题:

第1部分 :

public class Test {

    public static void main(String[] args) {

        System.out.println("Main Started");
        Child c = new Child();          //Instantiating Child Class
        System.out.println("Main Ended");
    }

}

class Father{

    Father(){                           //Father Class Default Constructor
        System.out.println("I am in Father");
    }

    void show(){
        System.out.println("Hello World");
    }
}

class Child extends Father{

    Child(){                            //Child Class Default Constructor
        System.out.println("I am in Child");
    }
}

输出 :

Main Started
I am in Father
I am in Child
Main Ended

这就是我知道在编译时发生的事情

class Child extends Father{

    Child(){                            //Child Class Default Constructor
        super();
        System.out.println("I am in Child");
    }
}

Father这里我的问题是,由于在执行 Class 的默认构造函数之前,它会进入Class 的默认构造函数Child,是否有创建对象Father

如果是这样,那么它被分配给什么?还是类似于匿名对象,例如new Father();. 是否Object每次都调用构造函数?

第2部分

每次我为 Class 创建一个对象时,都会使用within调用 ClassChild的默认构造函数。Fathersuper();Child()

当我试图通过Father使用Child对象调用任何方法时会发生什么?它会再次创建一个匿名对象Father,使用该对象执行然后留给它处理Garbage Collector吗?

正因为如此,这不会仅仅因为我们试图多次访问 supper 类的成员而导致大量的内存浪费。

在上述场景中,内存管理将如何进行?

标签: javaobjectinheritanceconstructor

解决方案


当您创建一个Child实例时,您并没有创建一个额外 Father的实例。该Child实例也是一个Father实例,因为Childextends FatherChild是一种特定的类型Father

显示这一点的一种巧妙方法是System.identityHashCode在两个类中打印,并看到 theFatherChilld构造函数都与相同的内存地址相关:

public class Test {
    public static void main(String[] args) {

        System.out.println("Main Started");
        Child c = new Child();          //Instantiating Child Class
        System.out.println("Main Ended");
    }

}

class Father{

    Father(){                           //Father Class Default Constructor
        System.out.println("I am in Father in address " + System.identityHashCode(this));
    }

    void show(){
        System.out.println("Hello World");
    }
}

class Child extends Father{

    Child(){                            //Child Class Default Constructor
        System.out.println("I am in Child in address " + System.identityHashCode(this));
    }
}

还有一个示例输出:

Main Started
I am in Father in address 2001049719
I am in Child in address 2001049719
Main Ended

推荐阅读