1

VectorやRasterなどのShapeImpオブジェクトにShapeオブジェクトを渡したい。CircleとSquareのコンストラクターの内部から「this」を渡そうとするとエラーが発生します。具体的な形状をVectorまたはRasterのいずれかに渡したい。

行でのNetbeansエラー

super(platform、x、y、this、 "Circle999");

「スーパータイプコンストラクターが呼び出される前にこれを参照することはできませんコンストラクターでこれをリークする」

package dp.bridge;

//-------Abstraction-------//

//----Abstraction-Specialization----------//
abstract class Shape{

    protected ShapeImpl platform;
    protected String type;

    Shape(String p, int x, int y, Circle s, String type){
        this.type = type;
        if(p.equals("vector"))
            platform = new Vector(x,y,s);
         if(p.equals("raster"))
            platform = new Raster(x,y,s);
    }

    public String getType() {
        return type;
    }

    
     abstract public void draw();
}
class Circle extends Shape{



    Circle(String platform, int x, int y){
        super(platform, x,y, this, "Circle999");
        
    }

    public void draw(){
        System.out.println("Circle: draw()");
        platform.draw();
    }
    
}

class Square extends Shape{

     Square(String platform, int x, int y){
        super(platform, x,y,this, "Square778");
     }

    public void draw(){
        System.out.println("Square: draw()");
        platform.draw();
    }

}

//----Abstract-Implementation------//
interface ShapeImpl{
    public void draw();

}

//--------Concreate implemenations--------//
class Raster implements ShapeImpl{

    int _x;
    int _y;
    Shape s;
    Raster(int x, int y, Shape s){
        _x = x;
        _y = y;
        this.s = s;
    }

    public void draw(){
        System.out.println("Drawing Raster "+s.getType()+ " at (" +_x + "," + _y +")");

    }
}

class Vector implements ShapeImpl{

    int _x;
    int _y;
    Shape s;
    Vector(int x, int y, Shape s){
        _x = x;
        _y = y;
        this.s = s;

    }

    public void draw(){
        System.out.println("Drawing Vector "+s.getType()+ " at (" +_x + "," + _y +")");

    }


}

//-----Client-------//
class Client{

    
    public static void main(String atgsp[]){
       Shape[] shapes= {new Circle("raster", 10, 40), new Square("vector", 2,2)};

        for(Shape s:shapes){
            s.draw();
        }
    }
}
4

1 に答える 1

1

オブジェクトをそれ自体に渡しますか?あなたはそれをする必要はありません(そしてあなたはそうすることができません、明らかに)。thisスーパークラスでは、現在のオブジェクトに解決されます。

thisしたがって、スーパーコンストラクターに引数として渡す代わりに、スーパーコンストラクターで使用this するだけです。new Vector(x, s, this)

于 2011-11-03T06:48:35.160 に答える