Issue
How I can to fix the error:
Exception in thread "main"java.lang.StackOverflowError at Rectangle.Square.setHeight(Square.java:25)
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height){
this.width=width;
this.height=height;
}
public void setWidth(int width){
this.width=width;
}
public int getWidth(){
return width;
}
public void setHeight(int height){
this.height=height;
}
public int getHeight(){
return height;
}
public int getSquare(){
return height*width;
}
}
public class Square extends Rectangle{
public Square(int width, int height)
{
super(width, height);
if(width!=height)
{
System.out.println("asdasdasdasd adasdasd");
}
}
public Square(int width)
{
super(width, width);
}
public void setWidth(int width)
{
setWidth(width);
setHeight(width);
}
public void setHeight(int height)
{
setHeight(height);
setWidth(height);
}
}
public class main {
public static void main(String[] args) {
Rectangle sq= new Square(20);
System.out.println(sq.getSquare());
sq.setHeight(30);
System.out.println(sq.getSquare());
}
}
Solution
In you Square class when you are calling the setHeight and setWidth method, you are recursively calling the same method, ie setWidth again calls the setWidth method leading to stackoverflow. You need to call super.setWidth instead of setWidth inside your square class.
Answered By - Naresh Sharma
Answer Checked By - David Goodson (JavaFixing Volunteer)