繁体   English   中英

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

[英]Should protected fields in an Abstract super class be accessed using super or this in sub-classes?

假设我有以下Abstract类。

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 ,但是我只是想知道如果有人想指定隐式参数,那么如何在实践中利用它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM