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.