0

私は次のように書かれた主な方法を持っています:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package excercise.pkg5;

/**
 *
 * @author Azraar
 */

    public class TestResizable {

    public static void main(String[] args) {

        Shape obj[] = new Shape[4];
        obj[0] = new Circle(10);
        obj[1] = new Rectangle(10, 20);
        obj[2] = new ResizableCircle(10);
        obj[3] = new ResizableRectangle(10, 20);

        for (int i = 0; i < obj.length; i++) {

            if (obj[i] instanceof ResizableCircle) {
                ResizableCircle r = (ResizableCircle) obj[i];
                obj[i].equals(r);

            }

            if (obj[i] instanceof ResizableRectangle) {
                ResizableRectangle r = (ResizableRectangle) obj[i];
                obj[i].equals(r);

            }

            System.out.println("");
            System.out.print("Object is - " + obj[i].name());
            System.out.print("\nObject Area is - " + obj[i].area());
            System.out.print("\nObject Perimeter is - " + obj[i].perimeter());
        }

    }
}

ResizableRectangle r = (ResizableRectangle) obj[i];resizable は実装であり、ResizableRectangle と ResizableCircle はそれを拡張し、resize メソッドをオーバーライドしているため、私は を使用しています。

instanceof resizbleRectange または resizableCircle の場合..この resize() メソッドを実行する必要があります..

obj[i].resize(0.5)その後、ループアウトして印刷されます。しかし、問題は、シンボルが見つからないと入力したときに、サイズ変更メソッドの真のインテリセンスを取得していないことです...

以下はクラス階層です...

ここに画像の説明を入力

編集:

添付のスクリーンショットでわかるように、shape は ROOT クラスです。オブジェクトが ResizeableClass と ResizeableRectangle のインスタンスである場合に resize メソッドにアクセスする方法を考えています。しかし、まだできません。

4

4 に答える 4

2

参照を呼び出す必要がありresize()ますResizeable

つまり、 が の場合obj[i]Resizeableキャストしてから呼び出す必要があります。obj[i]コンパイラは単純にそのようなオブジェクトを基本クラスの参照として扱っているため、単にそのようなオブジェクトを参照しているとアサートするだけでは十分ではありません。

例えば

if (obj[i] instanceof Resizeable) {
   ((Resizeable)obj[i]).resize(..);
}
于 2013-09-13T12:19:13.190 に答える
1

あなたは次のように宣言objしました

Shape obj[]

そのため、私が推測してobj[i]いるオブジェクトが返されます拡張されません。ShapeResizeable

于 2013-09-13T12:20:57.103 に答える
1

Shape メソッドのすべてのサブクラスが Resizable インターフェイスを実装しているわけではありません。obj[i]そのため、Resizeable クラスのインスタンスであるかどうかを確認してから、resize を呼び出す必要があります。

于 2013-09-13T12:25:17.133 に答える
0

これはついに機能しました...

    if (obj[i] instanceof ResizableCircle) {
        Resizable c = (ResizableCircle) obj[i];
        c.resize(5);

    }

    if (obj[i] instanceof ResizableRectangle) {
        Resizable r = (ResizableRectangle) obj[i];
        r.resize(10);

    }
于 2013-09-13T12:46:53.977 に答える