[英]JVM Memory Allocation
Hi I Have a question about inheritance. 嗨,我有一个关于继承的问题。 In Java, a subclass object have inside it an object of its superclass?
在Java中,子类对象在其内部具有其超类的对象?
When JVM allocate space for subclass object, allocates space for superclass field/method? 当JVM为子类对象分配空间时,是否为超类字段/方法分配空间? Thanks.
谢谢。
Example: 例:
class Bar {
public String field;
public Bar() {
this.field = "Bar";
}
}
class Foo extends Bar {
public String field;
public Foo() {
this.field = "Foo";
}
public void printFields() {
System.out.println("Base: " + super.field);
System.out.println("This: " + this.field);
}
}
In execution, will print "Bar" and "Foo". 在执行时,将打印“ Bar”和“ Foo”。 Where Java allocate space to mantain both value for "field"?
Java在哪里分配空间以保持“字段”的两个值?
Yes, Java will allocate space for two object references--one for Foo.field
and the other for Bar.field
. 是的,Java将为两个对象引用分配空间-一个用于
Foo.field
,另一个用于Bar.field
。 Loosely speaking, this can be a way to visualize an instance of Foo
in memory: 松散地说,这可以是一种可视化内存中
Foo
实例的方法:
[header] (references Foo.class, Bar.class, Object.class, among other details)
[Section for Bar]:
Field, declared type String, referencing a `java.lang.String` with value "Bar"
[Section for Foo]:
Field, declared type String, referencing a `java.lang.String` with value "Foo"
The offsets of these fields are known to the JVM and are used when reading/writing them. 这些字段的偏移量是JVM已知的,并在读取/写入它们时使用。
Note that this does not imply Foo
contains a Bar
, but rather Foo
is a Bar
and more. 请注意,这并不意味着
Foo
包含Bar
,而是Foo
是Bar
等。
In Java, a subclass object have inside it an object of its superclass.
在Java中,子类对象内部具有其超类的对象。
No. A subclass does not "contain" its parent object. 否。子类不“包含”其父对象。 Inheritance is an "is-a" relationship.
继承是“是”关系。 An instance of
Foo
is an instance of Bar
. Foo
的实例是Bar
的实例。 Not that Foo
contains Bar
. 并不是说
Foo
包含Bar
。
When JVM allocate space for subclass object, allocates space for superclass field/method?
当JVM为子类对象分配空间时,是否为超类字段/方法分配空间?
Yes. 是。 Although the subclass
Foo
has a field with the same name (hence "shadowing" the parent's field), there are still two fields allocated in memory. 尽管子类
Foo
具有相同名称的字段(因此“遮蔽了”父级的字段),但是在内存中仍然分配了两个字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.