猿问

抽象超类中的受保护字段是否应该在子类中使用 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”和“super”。使用一个比另一个更好吗?'super' 明确了该字段的来源。我知道我可以在balance不指定隐式参数的情况下使用,但我只是好奇如果想指定隐式参数,它在实践中是如何使用的。


郎朗坤
浏览 163回答 2
2回答

慕斯王

由于 CheckingAccount 从 Account 继承受保护的字段余额,因此使用super或this关键字访问 CheckingAccount 类中的字段余额并不重要。但是,我更喜欢“这个”。如果 Account 类(基类)中有一个受保护的方法,而 CheckingAccount 类中有一个被覆盖的方法,那么在这种情况下你必须小心使用super或this,因为它们不是同一个 body 实现!

汪汪一只猫

我认为您不应该使用任何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;    }}
随时随地看视频慕课网APP

相关分类

Java
我要回答