【发布时间】:2011-12-20 22:07:40
【问题描述】:
我想将 Shape 对象传递给 Vector 或 Raster 等 ShapeImp 对象。尝试从 Circle 和 Square 的构造函数内部传递“this”时出现错误。我想将具体形状传递给 Vector 或 Raster。
Netbeans 在线错误
super(平台, x,y, this, "Circle999");
"在调用超类型构造函数之前不能引用 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();
}
}
}
【问题讨论】:
-
如果对象尚未创建,则不能传递
this,因为它是一个空引用。并且当调用所有构造函数时将创建对象(您不能这样做,因为构造函数的一个参数是对尚未创建的对象本身的引用)
标签: java design-patterns bridge