java extends 关键字是引用变量吗?
is java extends keyword a reference variable?
我知道 extends 关键字在 java 中的作用,但我想了解 java 编译器在看到 extends 关键字时会做什么。
class A{
//some state
//some behavior
}
class B extends A{
}
在我看来,当编译器看到 extends 关键字时,它会创建超级 class 对象以在 subclass 中使用。我知道我们可以在 subclass 构造函数中使用 super 引用关键字来引用 super class 构造函数。
不,没有对超类对象的引用。当您执行 new B()
时,对于您的示例,会创建 one 对象,它具有 A
和 B
特征的组合,而不是单独的 B
和 A
之间存在关系的对象。 (这将是原型继承,它被用于多种语言,但不是 Java。)
super
不是对单独对象的引用。来自 JLS§15.11.2:
The form super
.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class.
有时,似乎必须是两个独立的对象,例如当您隐藏一个实例字段时:
class A {
private int field;
A(int value) {
this.field = value;
}
public void sayField() {
System.out.println("(A) field == " + this.field);
}
}
class B extends A {
private int field;
B(int aValue, int bValue) {
super(aValue);
this.field = bValue;
}
@Override
public void sayField() {
super.sayField();
System.out.println("(B) field == " + this.field);
}
}
如果你这样做:
B b = new B(1, 2);
b.sayField();
...你得到 (live copy)
(A) field == 1
(B) field == 2
如果只有一个对象,为什么 A#sayField
中的 this.field
与 B#sayField
中的 this.field
使用不同的 field
?答案是:那个对象中有两个 field
字段。编译器告诉 A#sayField
中的代码使用第一个,B#sayField
中的代码使用第二个。
我知道 extends 关键字在 java 中的作用,但我想了解 java 编译器在看到 extends 关键字时会做什么。
class A{
//some state
//some behavior
}
class B extends A{
}
在我看来,当编译器看到 extends 关键字时,它会创建超级 class 对象以在 subclass 中使用。我知道我们可以在 subclass 构造函数中使用 super 引用关键字来引用 super class 构造函数。
不,没有对超类对象的引用。当您执行 new B()
时,对于您的示例,会创建 one 对象,它具有 A
和 B
特征的组合,而不是单独的 B
和 A
之间存在关系的对象。 (这将是原型继承,它被用于多种语言,但不是 Java。)
super
不是对单独对象的引用。来自 JLS§15.11.2:
The form
super
.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class.
有时,似乎必须是两个独立的对象,例如当您隐藏一个实例字段时:
class A {
private int field;
A(int value) {
this.field = value;
}
public void sayField() {
System.out.println("(A) field == " + this.field);
}
}
class B extends A {
private int field;
B(int aValue, int bValue) {
super(aValue);
this.field = bValue;
}
@Override
public void sayField() {
super.sayField();
System.out.println("(B) field == " + this.field);
}
}
如果你这样做:
B b = new B(1, 2);
b.sayField();
...你得到 (live copy)
(A) field == 1 (B) field == 2
如果只有一个对象,为什么 A#sayField
中的 this.field
与 B#sayField
中的 this.field
使用不同的 field
?答案是:那个对象中有两个 field
字段。编译器告诉 A#sayField
中的代码使用第一个,B#sayField
中的代码使用第二个。