【问题标题】:Should protected fields in an Abstract super class be accessed using super or this in sub-classes?抽象超类中的受保护字段是否应该在子类中使用 super 或 this 访问?
【发布时间】:2018-11-13 15:50:24
【问题描述】:

假设我有以下抽象类。

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,但我只是好奇如果想指定隐式参数,它在实践中是如何使用的。

【问题讨论】:

    标签: java inheritance abstract-class


    【解决方案1】:

    由于 CheckingAccount 从 Account 继承受保护字段 balance,因此使用 superthis 关键字访问 CheckingAccount 类中的字段 balance 并不重要.不过,我更喜欢“this”。

    如果 Account 类(基类)中有受保护的方法,并且 CheckingAccount 类中有其覆盖的方法,则必须谨慎使用 superthis在这种情况下,因为它们不是同一个主体实现!

    【讨论】:

      【解决方案2】:

      我认为您不应该使用任何 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;
          }
      }
      

      【讨论】:

      • 请注意,您不能覆盖变量。这里发生的事情是隐藏的,CheckingAccount 实际上会有两个变量
      • CheckingAccount 是否从 Account 扩展而来?如果没有扩展,为什么在这里 super(Id, balance) ?如果是 Extending,为什么还要在 CheckingAccount 类中声明余额?
      猜你喜欢
      • 2013-05-27
      • 2015-10-07
      • 2011-10-16
      • 2017-12-09
      • 2013-03-25
      • 2012-12-01
      • 2015-08-02
      • 1970-01-01
      • 2020-01-12
      相关资源
      最近更新 更多