I am working on a project that is giving this error " implicit super constructor Shape2D is undefined. Must explicity invoke another Constructor" and dont really understand.
Here is my Shape Class
import java.awt.Color;
import java.lang.Comparable;
abstract class Shape implements Comparable<Shape>{
private final int id;
private final String name;
private final String description;
private Color color;
//abstract method
abstract double area();
abstract double perimeter();
//get and set and non-abstract method
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
//non default constructor
public Shape(int id, String name, String description, Color color) {
this.id = id;
this.name = name;
this.description = description;
this.color = color;
}
@Override
public int compareTo(Shape o) {
return 0;
}
@Override
public String toString() {
return String.format("%s,%s,%s,%s",id,name,description,color);
}
}
and here is my Shape2D class that will give the width and height variable
import java.awt.Color;// this is where the problem occur. if i remove it, the abstract class has an error " Implicit super constructor Shape() is undefined for default constructor. Must define an explicit
constructor and Implicit super constructor Shape() is undefined. Must explicitly invoke another constructor"
abstract class Shape2D extends Shape {
public final double height;
public final double width;
Shape2D(height , width){
this.height = height;
this.width = width;
}
public Shape2D(int id, String name, String description, Color color) {
super(id, name, description, color);
}
}
I have a super class that
As you are extending the Shape
class in Shape2D
, from Shap2D's
constructor java implicitly calls the super class's constructor if you do not specify. So, currently above code would be like below,
Shape2D(height , width){
super(); //this line will automatically added, when code complies.
this.height = height;
this.width = width;
}
Because In your parent class Shape
you do not have any args constructor. It will not find any suitable constructor and will give an error as you mentioned. To avoid this you can explicitly mention which super class's constructor to call. So, the code will look like below:
Shape2D(height , width){
super(1,"triangle","test",Color.yellow); //Called parent class's constructor.
this.height = height;
this.width = width;
}
You have used super(id, name, description, color);
in your other constructor, but one can always create an new instance using Shape2D(height , width)
constructor. In this case, Java needs to make sure that the parent class constructor gets called.