【问题标题】:Java - Using a Conditional To Specify a Parameter in a Super MethodJava - 使用条件在超级方法中指定参数
【发布时间】:2015-09-05 03:12:56
【问题描述】:

我有一个从另一个类扩展而来的参数化方法。抽象类 Account 是父类,SavingsAccount 继承自它的构造函数。这个构造函数是一个参数化的构造函数。我想使用条件来允许(或禁止)某些值进入双 init_balance 字段,然后该字段将为父构造函数调用 super()。

if(init_balance < minimumBalance){
    //Print message to user asking for larger deposit. (is this enough to do?)
}

但是 java 语言要求我首先将调用父构造函数放在子构造函数中。所以我无法通过子构造函数过滤进入父构造函数的内容。

这是我在gist上的代码

【问题讨论】:

    标签: java class inheritance constructor super


    【解决方案1】:

    如果你想保持基于构造函数的对象创建,你可以想出这个:

    public class SavingsAccount extends Account {
    
      private SavingsAccount(String init_id, double init_balance)
      {
        super(init_id, validate(init_balance));
      }
    
      public static double validate(double init_balance) {
        if (init_balance < minimumSavings) {
            System.out.println("Message");
            throw new RuntimeException("Message"); // or handle this error
        }
        return init_balance;
      }
    }
    

    然而 - 看看你的例子,我可能会选择在构造函数之外进行验证。

    【讨论】:

      【解决方案2】:

      我相信这回答正确:Why do this() and super() have to be the first statement in a constructor?

      但基本上你需要把super(init_id, init_balance);放在第一位。

      【讨论】:

        【解决方案3】:

        正如其他人所说,该语言要求您首先调用超类构造函数(我相信这是为了避免在初始化超类字段之前子类构造函数访问超类字段或方法可能出现的问题)。除了浪费几纳秒之外,这通常不是问题。如果这真的是一个问题——超类构造函数做了一些你不想在违反约束时做的事情——将子类构造函数设为私有并使用工厂方法:

        class SavingsAccount extends Account {
        
            private SavingsAccount(String init_id, double init_balance)
            {
                super(init_id, init_balance);
            }
        
            public static SavingsAccount newSavingsAccount(String init_id, double init_balance) {
                if (init_balance < minimumSavings) {
                    System.out.println("Sorry, but you need to give us moar moneyz!");
                    throw new Exception("Not enough money.");
                }
                return new SavingsAccount(init_id, double init_balance);
            }
        }
        

        您不能再在其余代码中说new SavingsAccount(id, balance);你必须说SavingsAccount.newSavingsAccount(id, balance)。但是这个价格可能是值得的,这取决于您的需求。

        【讨论】:

          【解决方案4】:
          class Account
          {
              public Account(String init_id, double init_balance)
             {
                 super(init_id, init_balance);
             }
             public void condition_Method()
             {
                //your condition create object only if condition satisfied or else give                  //error message
          
                Account object=new Account(init_id, init_balance);
             }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-12-13
            • 1970-01-01
            • 2021-12-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-04-10
            相关资源
            最近更新 更多