-1

子クラス メソッドをスーパー クラス オブジェクトに呼び出したいのですが、子クラスで別の整数を宣言したため、例外が発生しています。これを実現するための回避策はありますか?

public static void main(String[]args){

    A a = new A(2,3);
    B b = new B(3,5,6);

    System.out.println("A object: ");
    a.showij();
    System.out.print("sum = ");
    ((B) a).sum(); < ==== this line gives me the error, can't cast
    System.out.println("B object: ");
    b.showij();
    System.out.print("sum = ");
    b.sum();

}

public class B extends A {

int k;

public B(){
    super();
}

public B(int a, int b, int c) {
    super(a, b);
    k = c;
}

public void sum(){
    System.out.println( i + j + k);
}
}


public class A {

int i,j;

public A() {

}

public A( int a, int b){
    i = a;
    j = b;      
}

public void showij(){
    System.out.println("\ti: " + i + " j: " + j);
}
}

*編集:ここにすべてがあります

4

2 に答える 2

1

B が A を拡張する場合、これは依然として A が別のクラスであることを意味します。A のみをインスタンス化すると、B とは無関係であるため、B にキャストできません。

派生クラスは常にそのスーパー クラスにキャストできるため、B を A にキャストできます。実際、これにはキャストさえ必要ありません。しかし、これは不可能です。

B が A を拡張するとします。

  B b = new B(1,2,3,4,5);
  A a = b; <- This is valid.

  a.sum(); 

これは構文的には正しいですが、B のオブジェクトであるため、B の sum 関数を呼び出すことになります。

ただし、Java では、C++ のようにクラス外でスーパー関数を明示的に呼び出すことはできません。関数でこれを決定し、次のように B から呼び出す必要があります。

class B extends A
{
    @Override
    public int sum()
    {
        super.sum();
    }
}

これが望ましくない場合は、派生クラスによって上書きされない別の関数名を宣言する必要がありますが、派生できないことを確認するためにクラスを final にしない限り、特定の動作に依存することはできません。

アップデート

コード例:

public class A
{
    private int mI;
    private int mJ;

    public A(int i, int j)
    {
        mI = i;
        mJ = j;
    }

    public int sum()
    {
        return mI+mJ;
    }

    public void showij()
    {
        System.out.println("I: "+ mI + " J: "+mJ);
    }

    public void print()
    {
        System.out.println("A called "+ sum());
    }
}

クラス B:

public class B
    extends A
{
    private int mK;

    public B(int i, int j, int k)
    {
        super(i, j);
        mK = k;
    }

    public int sum()
    {
        return super.sum()+mK;
    }

    public void showk()
    {
        System.out.println("K: "+ mK);
    }

    public void print()
    {
        System.out.println("B called "+ sum());
    }
}

テストメイン:

public class test
{
    public static void main(String[] args)
    {
        A a = new A(1, 2);
        B b = new B(3, 4, 5);

        a.print();
        b.print();
        a.showij();
        b.showij();
        b.showk();
        a = b;
        b.print();
    }
}
于 2013-06-30T05:59:57.403 に答える
0

型をそのサブクラスにキャストすることは有効であるため、コードはコンパイルされます。ただし、これが原因でクラス キャストの実行時例外が発生しました。

A a = new A(2,3); --> Your instance is of type A

((B) a).sum();  --> and you are casting it to B, which cannot happen because the object is not of type B

しかし、このステートメントはうまくいったでしょう

A a = new B(2,3, 6); --> As per the declaration type of instance is A but the actual instance created is B. So even if a is cast to B it works.
((B) a).sum();
于 2013-06-30T06:22:14.057 に答える