2

私はオラクルのチュートリアルを勉強していて、ここから「タイプとしてのインターフェースを使用する」の章に関していくつか質問があるので、メソッドfindLargestを呼び出す方法を理解しようとしています。

理解を深めるためにビットソースコードを変更しようとしましたが、何も役に立ちません:(

これが私のコードです:

public class RectanglePlus implements Relatable {

    public int width = 0;
    public int height = 0;

    public RectanglePlus() {
    }

    public RectanglePlus(int w, int h) {
        width = w;
        height = h;
    }

    // a method for computing the area of the rectangle
    public int getArea() {
        return width * height;
    }

    // a method required to implement the Relatable interface

    public int isLargerThan(Relatable other) {
        RectanglePlus otherRect = (RectanglePlus) other;
        if (this.getArea() < otherRect.getArea()) {
            return -1;
        } else if (this.getArea() > otherRect.getArea()) {
            return 1;
        } else {
            return 0;
        }
    }

    // and here is the method that i cant invoke
    public RectanglePlus findLargest(RectanglePlus object1,
            RectanglePlus object2) {
        Relatable obj1 = (Relatable) object1;
        Relatable obj2 = (Relatable) object2;
        if ((obj1).isLargerThan(obj2) > 0) {
            return object1;
        } else {
            return object2;
        }
    }

    public static void main(String[] args) {
        RectanglePlus test1 = new RectanglePlus(10, 20);
        RectanglePlus test2 = new RectanglePlus(20, 20);
    }
}

では、test1とtest 2を比較するためにfindLargeメソッドを呼び出すにはどうすればよいですか?(メソッドisLargerThanから最大のオブジェクトを見つけることは意味がないことはわかっていますが、原則を理解しようとしています)

静的なメソッドではないので、「RectanglePlus.findLarger(test1、test2)」とだけ言うことはできません。

どうすればいいですか?

4

1 に答える 1

2

findLargestではないためstatic、anyを使用RectanglePlusして関数を呼び出すことができます。

test1.findLargest(test1,test2);

また

test2.findLargest(test1,test2);
于 2012-08-03T14:28:21.057 に答える