I want to pass a Shape object to ShapeImp object like Vector or Raster. Error comes when trying to pass "this" from inside constructors of Circle and Square. I want to pass the concrete shapes to either Vector or Raster.
Netbeans error at line
super(platform, x,y, this, "Circle999");
"cannot reference this before supertype constructor has been called
Leaking this in constructor"
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();
}
}
}
You are passing an object to itself? You don’t need to do that (and you can’t, obsiouly).
thisin the superclass will still resolve to the current object.So instead of passing
thisas argument to the super-constructor, simply usethisin the superconstructor:new Vector(x, s, this)