java - 每次实例化子类时都会创建超类对象吗?
问题描述
这是一个两部分的问题:
第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
的默认构造函数。Father
super();
Child()
当我试图通过Father
使用Child
对象调用任何方法时会发生什么?它会再次创建一个匿名对象Father
,使用该对象执行然后留给它处理Garbage Collector
吗?
正因为如此,这不会仅仅因为我们试图多次访问 supper 类的成员而导致大量的内存浪费。
在上述场景中,内存管理将如何进行?
解决方案
当您创建一个Child
实例时,您并没有创建一个额外 Father
的实例。该Child
实例也是一个Father
实例,因为Child
extends Father
。Child
是一种特定的类型Father
。
显示这一点的一种巧妙方法是System.identityHashCode
在两个类中打印,并看到 theFather
和Chilld
构造函数都与相同的内存地址相关:
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
推荐阅读
- oauth - 使用 Azure AD 身份验证访问本地 SAML/OAuth 保护的 SAP API(ADFS 联合)
- html - 将两个包含“过滤器”的 CSS 类应用于 HTML 元素
- java - Apache Beam 中嵌套的 Top N
- python - 表单未在 django admin 中保存电子邮件
- python - django 火车预订系统(订票)
- javascript - Python selenium how to execute execute_script on a JavaScript element with arguments
- elasticsearch - 在 nodejs 中使用 nock 测试 elasticsearch
- php - 触发 Woocommerce 自定义字段时出现致命错误
- javascript - 按子数组值分组并将字段带到主数组
- c++ - range-v3:调整已经实现迭代器接口的自定义类(开始/结束)