Khaines0625
Khaines0625

Reputation: 407

Stack OverFlow with inherited JPanels

So I'm writing a program that is fairly expansive and had a stack overflow error (No, I'm not using any kind of recursion, at least not directly.) I tried to recreate the situation with much simpler classes to see if it would also cause a stack overflow error and it did. Here they are:

First Class:

public class Thing 
{
    public static void main(String[] args) 
    {
          OtherThing thing = new OtherThing();
    }
}

Second Class:

public class OtherThing extends JPanel
 {
     protected int s =5;
     protected String blah = "asfasd";
     public OtherThing()
     {
        OtherOtherThing thing2 = new OtherOtherThing();
     }
 }

Last Class:

public class OtherOtherThing extends OtherThing
 {
     public OtherOtherThing()
     {

     }
 }

This causes a stack overflow bouncing between OtherThing line 8 and OtherOtherThing line 4 (lines im sure are a little off now.)

I know that you can inherit from a class that has inherited from something else, the Java API is full of them. Whats wrong with this example?

Upvotes: 1

Views: 93

Answers (2)

Pham Trung
Pham Trung

Reputation: 11294

Because when OtherOtherThing is created, the constructor of its parent OtherThing is called, which created a new OtherOtherThing , and inside this OtherOtherThing, it will in turn create a new OtherOtherThing ..., which cause stackoverflow.

You can use lazy initialization or eager initialization in order to resolve it:

Lazy initialization:

public class OtherThing extends JPanel
 {
     protected int s =5;
     protected String blah = "asfasd";
     private OtherOtherThing other = null;
     public OtherThing()
     {

     }
     public void initialize(){
          other =  new OtherOtherThing();
     }
 }

Eager initialization:

 public class OtherThing extends JPanel
 {
     protected int s =5;
     protected String blah = "asfasd";
     private OtherOtherThing other = new OtherOtherThing();
     public OtherThing()
     {

     }

 }

Upvotes: 1

gknicker
gknicker

Reputation: 5569

What's wrong with this example?

The first thing a constructor does, unless otherwise specified, is to call the superclass constructor.

public OtherOtherThing()
{
    super(); // automatically added by compiler
}

So yeah, your code will continue to create new OtherOtherThings until the stack overflows.

Upvotes: 0

Related Questions