我试图了解子类的实例如何成为父类的实例。我的意思是,一旦创建,他们就会在内存中获得什么样的模型。
检查下面的代码片段
public class Parent {
public String log4jConfig;
public void setLog4jConfig(String log4jConfig){
System.out.println(this.getClass()); ---4
this.log4jConfig = log4jConfig;
}
public String getLog4jConfig() {
return log4jConfig;
}
}
public class Child extends Parent {
}
public class Mainclass {
public static void main(String[] args) {
Child obj = new Child(); // ---1
obj.setLog4jConfig("log4jConfig");
}
}
当我创建子类的实例时,它可以访问父类的所有方法,因为这些方法是继承的。
并且 this
代表当前类实例,那么为什么要获取 4 Child 的类名呢?因此,如果扩展时 CHILD 是父类,那么它在内存中的位置如何,我试图可视化内存中父类和子类的坐姿计划,其中父类的 this
成为子类的实例。
或者扩展时,它是否为在内存中继承的相应父类和子类创建两个方法副本?
请帮忙..!
谢谢
最佳答案
When child class Instance becomes Parent class Instance
它不会“成为”。它"is"。 子
是 parent
,就像香蕉
是 水果
。
And
this
represents the current class Instance
this
表示当前的 class 实例。运行时只有一个对象,而不是多个对象,也不是基于类层次结构的多层。有一个对象。期间。
And this represents the current class Instance, So why am getting at 4 Child's class name ?
运行时存在的每个实例/对象都是使用new
关键字创建的。使用 new
的类是该对象的运行时类(这是一个简化的语句)。运行时类是调用 getClass()
时返回的类。
在所有这些情况下,Child
是 obj
指向的实例的运行时类:
Child obj = new Child();
Parent obj = new Child();
//and all the possible intermediate parents, until
Object obj = new Child();
OR When extended, Does it creates a two copies of Methods for respective parent and child classes which are inherited in memory ?
最简单的思考方法是:
- 创建对象时,Java 知道该对象的运行时类(见上文)。
- 通过运行时类,它知道在该运行时类中声明的对象可以使用哪些方法和属性(在您的情况下为
Child
) - 通过运行时类,它知道从该对象的父类型(在您的情况下为
Parent
和Object
)继承了哪些方法和属性 - 通过运行时类,Java 知道将根据子类执行哪些继承和重写的方法(您没有重写的方法)。
因此,当您编写 this
时,您引用的是调用当前代码的单个对象。您可以使用 this
引用运行时类中声明的方法和属性以及可从父类(super class)型访问的方法和属性。
当您编写super
时,您仍然引用调用当前代码的单个对象。使用 super
引用的是在声明当前执行代码的父类中显式声明的方法或属性。
关于java - 当子类Instance变成父类Instance时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54977417/