0

要件

整数算術計算機をモデル化し、以下を含む既存のクラスICalculatorが利用可能であると想定します。


  • 計算機の現在のint値を格納するインスタンス変数currentValue

  • メソッドadd、sub、mul、およびdiv

    ICalculatorの各メソッドはint引数を受け取り、その操作をcurrentValueに適用して、currentValueの新しい値を返します。したがって、currentValueの値が8で、sub(6)が呼び出された場合、currentValueは値2になり、2が返されます。

したがって、ICalculatorに基づいてサブクラスICalculator1の定義を作成する必要があります。クラスICalculator1には、引数を受け取らず、currentValueを変更しない1つの追加メソッドsignがあります。代わりに、currentValueがそれぞれ正、ゼロ、または負のいずれであるかに応じて、1、0、または-1を返すだけです。

コード:

1 public class ICalculator1 extends ICalculator {
2 public int getCurrentValue() {return currentValue;} //**did not need this line**
3 
4 int sign() {
5 if(currentValue > -1) return 0; //changed to**int val = add(0);**
6 else if(currentValue < 0) return -1; //changed to **if (val > 0) return 1;**
7 else return 1; //changed to **else if (val < 0) return -1;**
8 }}

エラーメッセージ:

ICalculator1.java:2: error: currentValue has private access in ICalculator
public int getCurrentValue() {return currentValue;}
                                     ^
ICalculator1.java:5: error: currentValue has private access in ICalculator
if(currentValue > -1) return 0;
   ^
ICalculator1.java:6: error: currentValue has private access in ICalculator
else if(currentValue < 0) return -1;
        ^
3 errors

私が間違っていることがわかりませんか?

4

1 に答える 1

3

したがって、currentValueプライベートであるため、サブクラス内で直接アクセスすることはできません。メソッドは実際にはの値を返すcurrentValueため、たとえば次のように、サブクラス内でこれを利用できます。

public int sign() {
   int val = add(0);   // add 0 and return currentValue
   if (val > 0) return 1;
   else if (val < 0) return -1;
   else return 0;
}

他の人が示唆しているように、の可視性を変更できる場合は、それを保護して、そのハックcurrentValueは必要ありません。add(0)ただし、変更できない場合はICalculator、これが1つの可能性です。

于 2012-10-26T02:12:48.253 に答える