2017-09-02 4 views
2

スーパークラスに送信する前に、サブクラスで受け取った可変量の値をチェックする必要があります。 プライベートスーパークラス変数に送信する前にサブクラスの値を確認してください

この

//superclass 
public class Account 
{ 
    private double balance; 

    public Account(double amount) 
    { 
      balance = amount; 
    } 

    public Account() 
    { 
      this(0.0); 
    } 

    public void deposit(double amount) 
    { 
      balance += amount; 
    } 

    public void withdraw(double amount) 
    { 
      balance -= amount; 
    } 

    public double getBalance() 
    { 
      return balance; 
    } 
} 

これは私が私のサブクラスのために持っているもので、私は私のスーパーのために持っているもので、私は私が何とかチェックするために、「この(金額)」を使用することになっています考えて

public class SafeAccount extends Account 
{ 

    public SafeAccount(double amount) 
    { 
     // something to check if amount is positive before sending it to 
     super 

     // if it's not positive, use no argument constructor to set balance == 
     0.0 
    } 
} 

しかし、私はそれがどのように機能するか正確にはわかりません。

+0

これは[LSP](https://en.m.wikipedia.org/wiki/Liskov_substitution_principle#Principle)に違反します: "*サブタイプで前提条件を強化することはできません*" - あなたのデザインを再考したいかもしれません。 –

答えて

4

super()はコンストラクタ本体の最初の文でなければなりません。その前にチェックを行うことはできません。周り

シンプルな作品:あなたが本当に無引数のコンストラクタを使用する必要がある場合

public class SafeAccount extends Account 
{ 

    public SafeAccount(double amount) 
    { 
    super(Math.max(0.0, amount)); 
    } 
} 

は周りより複雑な作業は次のようになります。あなたのサブクラスで

public class Account { 
    Account() { 

    } 

    Account(double x) { 

    } 
} 

public class SafeAccount extends Account { 
    private SafeAccount() { 

    } 

    private SafeAccount(double amount) { 
     super(amount); 
    } 

    public static SafeAccount boo(double x) { 
     if (x < 0.0) { 
      return new SafeAccount(); 
     } 
     return new SafeAccount(x); 
    } 
} 

使用privateコンストラクタは、コンストラクタからinstantionを防ぐために必要なチェックを行うファクトリメソッドを提供します。

2

次の文

class SafeAccount extends Account { 
    public SafeAccount(int balance) { 
     super(balance > 0? balance: 0); 
    } 
} 

を使用しかし、一般的な継承階層の設計の正しさのために再チェックする必要がありますすることができます。

関連する問題