gpt4 book ai didi

java - 访问父类字段 "this.field"VS "super.field"

转载 作者:行者123 更新时间:2023-12-02 07:41:38 26 4
gpt4 key购买 nike

我想知道使用 thissuper 访问父类字段的区别。

我们有以下名为 ListItem 的抽象类,它扩展了 Node 类。

public abstract class ListItem {
protected ListItem rightLink=null;
abstract ListItem next();
}

Node 类中包含以下代码:

public class Node extends ListItem {
@Override
ListItem next() {
return this.rightLink;
}

但是如果我们使用代码 super.rightLink,我在编译时或运行时不会收到任何错误。我只是想知道两者之间有什么区别,是否有完成任务的最佳实践?

最佳答案

说明

没关系在这种情况下,没有区别。

该字段在父类中声明。因此从技术上来说 super.rightLink 是最有意义的。但是,superthis 仅与解决变量阴影的不明确情况相关。

在这种情况下,最好的方法是省略任何前缀,只输入 rightLink。但这有点基于意见。

<小时/>

示例

假设我们有以下内容

public class Parent {
int variable = 1; // Field
}

public class Child extends Parent {
int variable = 2; // Field

public void foo() {
int variable = 3; // Local variable

System.out.println(variable); // 3
System.out.println(this.variable); // 2
System.out.println(super.variable); // 1
}
}
<小时/>

深入

因此,我们遇到了 3 个不同变量的情况,它们都位于不同的作用域中,但它们具有相同的名称。当您只输入 variable 时,Java 将引用作用域最低的变量。这将是方法中的局部变量。如果你想访问你的字段,你需要执行this.variable。如果你想访问你父级的字段,你需要执行super.variable

同样,我们这里有三个不同的变量。

  • 无前缀:最低范围
  • this:范围最低的字段
  • super:范围最低的字段,从直接父级开始

但是,在您的具体示例中,我们根本没有名称隐藏。只有一个名为 rightLink 的变量。因此,所有三个变体都引用完全相同的变量。

在这种情况下,最好是根本不使用前缀,仅使用 rightLink

<小时/>

JLS

让我们看看 Java 语言规范如何定义 this.super.

对于这个。,请参阅JLS§15.8.3 :

When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method or default method was invoked (§15.12), or to the object being constructed. The value denoted by this in a lambda body is the same as the value denoted by this in the surrounding context.

对于 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.

关于java - 访问父类字段 "this.field"VS "super.field",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54690247/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com