抽象超类中的受保护字段应该使用super访问还是在子类中使用this访问



假设我有以下抽象类。

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;
}
}

访问受保护成员时,子类的上下文中允许使用"this"one_answers"super"。用一个比用另一个好吗?"super明确了该字段的来源。我知道我可以在不指定隐式参数的情况下使用balance,但我只是想知道如果想要指定隐式的参数,在实践中如何使用它。

由于CheckingAccount从Account继承了受保护的字段余额,因此使用super关键字访问CheckingAccount类中的字段余额并不重要。不过,我更喜欢"这个"。

如果Account类(基类(中有受保护的方法,而CheckingAccount类中有其重写的方法,则在这种情况下,您必须小心使用superthis,因为它们不是同一个主体实现!

我认为不应该使用任何protected字段来强制封装。提供protected void addToBalance(double value)方法将是更干净的方法。

如果想指定隐式参数,我只是想知道在实践中如何使用它

出于某种学术原因,以下是它的区别:

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 {
// overwrite existing field
protected double balance;
public CheckingAccount(String Id, double balance) {
super(Id, balance);
this.balance = balance;
if(super.balance > 10_000) this.balance += 200;
}
}

最新更新