1

I'm newbie to java. I learned about objects within objects today and tried it with the classes below but encountered a stack overflow error during construction.

I have 3 classes: Shape, Rectangle which extends Cube, and a demo class.

public class Shape{
    public Shape() {
        System.out.println("Constructor of Shape.");
    }   

    public Rectangle rec = new Rectangle(10, 14);
}

public class Rectangle extends Shape{
    public Rectangle(int width, int height) {
        super();
        this.width = width;
        this.height = height;
    }

    int width, height;
}

public class DemoShape{
    public static void main(String[] args) {
        Shape c = new Shape();
        System.out.println(c.rec.getArea());
}

Error return:

Exception in thread "main" java.lang.StackOverflowError
    at ObjectWithinAnObject.p2.Rectangle.<init>(Rectangle.java:6)
    at ObjectWithinAnObject.p2.Shape.<init>(Shape.java:9)
    at ObjectWithinAnObject.p2.Rectangle.<init>(Rectangle.java:6)
    at ObjectWithinAnObject.p2.Shape.<init>(Shape.java:9)
    at ObjectWithinAnObject.p2.Rectangle.<init>(Rectangle.java:6)
    at ObjectWithinAnObject.p2.Shape.<init>(Shape.java:9)

I changed Cube to Shape to clear confusion.

Ivy
  • 41
  • 5
  • I doubt this is the problem, but it's not a good idea for the superclass to contain a direct reference to a subclass (the cube.rec instance variable). I'm also having a hard time understanding why a rectangle (a 2d figure) would extend a cube (a 3d figure). – NomadMaker Apr 23 '20 at 03:02
  • 1
    You have a circular / recursive dependency here. `Cube` has a `Rectangle` member, so when you create an instance of `Cube`, it needs to create that `Rectangle rec`. `Rectangle` in turn is derived from cube, so when you create a `Rectangle`, it calls the `Cube` constructor to create the `Cube` base object, which has a `Rectangle`... and so on till your stack overflows. – Robert Apr 23 '20 at 03:03
  • 2
    @NomadMaker In fact, that is the problem. (And you're right that the superclass should not refererence, or even know about, its subclass.) To construct a Cube, it must create a Rectangle, which is itself a Cube, which calls the Cube constructor, which must create a Rectagle, which is itself a Cube, which calls the Cube constructor, which must create a Rectangle, ... – David Conrad Apr 23 '20 at 03:04
  • I see that now. Just too tired to figure that out on my own, just recognized it as bad. – NomadMaker Apr 23 '20 at 03:05

0 Answers0