我有一个类A,它扩展了抽象类B。
让B有一个 protected 字段值
我想在 A 中使用这个字段。如果 A 没有 value,我可以编写 this.value
从 B 获取它。
与super.value
有什么区别吗?
最佳答案
这取决于...
如果只有类B
声明了一个字段value
,那么这并不重要。但如果类 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
JLS says
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
因此,由于父类(super class) 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
引用在类B
中声明的继承字段value
。但是,如果类 A
声明一个字段 value
,则 this.value
将引用类 A
中的字段.
关于java - 使用 "this"意味着 "super"使用字段可以吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60874955/