2011-11-03 7 views
1

Vector 또는 Raster와 같은 ShapeImp 객체에 Shape 객체를 전달하려고합니다. 서클과 스퀘어의 내부 생성자에서 "this"를 전달하려고하면 오류가 발생합니다. 콘크리트 도형을 Vector 또는 Raster에 전달하고 싶습니다.Java에서 Bridge 패턴을 구현할 때 오류가 발생했습니다.

라인에

넷빈즈 오류

슈퍼 (플랫폼, X, Y,이 "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(); 
     } 
    } 
} 
+1

:

그래서 그 대신 superconstructor와에 인수로 this를 전달하는, 단순히에 superconstructor와를 this를 사용 빈 참조입니다. 그리고 모든 생성자가 호출 될 때 객체가 생성됩니다 (생성자의 한 인수가 아직 생성되지 않은 객체 자체에 대한 참조이므로 수행 할 수 없습니다). –

답변

1

당신은 그 자체로 객체를 전달하는

"슈퍼 생성자는 생성자에서이 누출 라는되기 전에이를 참조 할 수 없습니다"? 당신은 그렇게 할 필요가 없습니다 (그리고 당신은 할 수 없습니다, obsiouly). 수퍼 클래스에있는 this은 여전히 ​​현재 오브젝트로 해석됩니다. 그 이후, 객체가 아직 생성되지 않은 경우 당신은`this`을 통과 할 수 new Vector(x, s, this)

+0

해결 방법은 무엇입니까? 내가 여기서하려고하는 것을 얻을 수 있기를 바랍니다. – coder9

+0

두 번째 단락을 참조하십시오. – Bozho

+0

감사. superconstructor에서 "this"를 전달하는 것이 Super 클래스 자체의 인스턴스 만 전달할 것이라고 생각했습니다. :) 이제는 Concrete 클래스를 통과하는 것을 볼 수 있습니다! – coder9

관련 문제