簡體   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