我想将 Shape 对象传递给 Vector 或 Raster 等 ShapeImp 对象。尝试从 Circle 和 Square 的构造函数内部传递“this”时出现错误。我想将具体形状传递给 Vector 或 Raster。
Netbeans 在线错误
超级(平台,x,y,这个,“Circle999”);
“在调用超类型构造函数之前无法引用 this 在构造函数中泄漏 this”
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();
}
}
}