使用 "this" 意味着 "super" 可以使用字段吗
Is it fine to use "this" meaning "super" to use a field
我有一个 class A 扩展了一个摘要 class B。
让B有一个受保护的字段value
我想在A中使用这个字段。如果A没有值,我可以写this.value
从B获取它。
和super.value
有区别吗?
这取决于...
如果只有class B
声明了一个字段value
则无所谓。但是,如果 class A
也会声明一个字段 value
,那么这很重要:
看看这个例子:
public class A extends B {
private Object value = "A";
public void printValue() {
System.out.println(super.value);
System.out.println(this.value);
}
public static void main(String[] args) {
A a = new A();
a.printValue();
}
}
如果你运行这个代码输出是:
B
A
JLSsays
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
因此,由于 superclass B
声明了字段 value
,它被 super.value
引用。
关于关键字 this
JLS says:
... the keyword this
denotes a value that is a reference to the
object for which the instance method or default method was invoked ... The type of this
is the class or interface type T
within which the keyword this
occurs.
在您的例子中,this
的类型是 A
。因此 this.value
指的是在 class B
中声明的继承字段 value
。但是如果 class A
将声明一个字段 value
,那么 this.value
将引用 class A
.
中的字段
我有一个 class A 扩展了一个摘要 class B。
让B有一个受保护的字段value
我想在A中使用这个字段。如果A没有值,我可以写this.value
从B获取它。
和super.value
有区别吗?
这取决于...
如果只有class B
声明了一个字段value
则无所谓。但是,如果 class A
也会声明一个字段 value
,那么这很重要:
看看这个例子:
public class A extends B {
private Object value = "A";
public void printValue() {
System.out.println(super.value);
System.out.println(this.value);
}
public static void main(String[] args) {
A a = new A();
a.printValue();
}
}
如果你运行这个代码输出是:
B
A
JLSsays
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
因此,由于 superclass B
声明了字段 value
,它被 super.value
引用。
关于关键字 this
JLS says:
... the keyword
this
denotes a value that is a reference to the object for which the instance method or default method was invoked ... The type ofthis
is the class or interface typeT
within which the keywordthis
occurs.
在您的例子中,this
的类型是 A
。因此 this.value
指的是在 class B
中声明的继承字段 value
。但是如果 class A
将声明一个字段 value
,那么 this.value
将引用 class A
.