假设我有以下抽象类。
public abstract class Account {
protected String Id;
protected double balance;
public Account(String Id, double balance) {
this.Id = Id;
this.balance = balance;
}
}
以及以下子类
public class CheckingAccount {
public CheckingAccount(String Id, double balance) {
super(Id, balance)
if(super.balance > 10_000) this.balance += 200;
}
}
访问 protected 成员时,子类上下文中允许使用“this”和“super”。使用其中一种比另一种更好吗? 'super' 明确了该字段的来源。我知道我可以只使用 balance
而不指定隐式参数,但我只是好奇如果想指定隐式参数,在实践中如何利用它。
最佳答案
由于 CheckingAccount 继承了 Account 的 protected 字段 balance,因此使用 super 或 this 关键字访问 CheckingAccount 类中的字段余额并不重要。不过,我更喜欢“这个”。
如果 Account 类(基类)中有 protected 方法,并且 CheckingAccount 类中有其重写的方法,则必须小心使用 super 或 this在这种情况下,因为它们不是同一个主体实现!
关于java - 抽象父类(super class)中的 protected 字段是否应该在子类中使用 super 或 this 来访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53284683/