java - 使用 "this"意味着 "super"使用字段可以吗

标签 java inheritance this super

我有一个类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 of this is the class or interface type T within which the keyword this occurs.

在您的情况下,this 的类型是 A。因此,this.value 引用在类B 中声明的继承字段value。但是,如果类 A 声明一个字段 value,则 this.value 将引用类 A 中的字段.

关于java - 使用 "this"意味着 "super"使用字段可以吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60874955/

相关文章:

java - Android ExpandableListView 填充了两次

java - Java中如何更改背景?

javascript - V8 中的 ES6 箭头函数词法 this

java - 我什么时候应该在类里面使用 "this"?

C++ - 从基类运算符内部调用基类重写的虚方法

javascript - jQuery - 从具有相同类的元素中获取不同的值

java - hibernate中子对象列表的条件查询

java - Android Studio 中的 Java 随机数

Java继承2个接口(interface),方法相同

c++宏导入基模板类的所有名称