1

My Code:

(causes a Stack Overflow Error)

public class Overloads {
    String uniqueID;    
    Overloads ov2=new Overloads();

    public static void main(String[] args) {
        System.out.println("IN MAIN");
    }

    public void setUniqueID(String theID) {
        // II lots of validation code, and then:
        uniqueID = theID;
        System.out.println(uniqueID);
    }
}

This Code Works Fine:

public class Overloads {
    String uniqueID;   

    public static void main(String[] args) {
          Overloads ov2=new Overloads();
          System.out.println("IN MAIN");
    }

    public void setUniqueID(String theID) {
        // II lots of validation code, and then:
        uniqueID = theID;
        System.out.println(uniqueID);           
    }
}
1
  • 3
    The problem with your first code is that creating an instance of Overloads involves creating another instance of Overloads thanks to having this field: Overloads ov2=new Overloads();. Commented Oct 7, 2013 at 7:29

2 Answers 2

12

The presence of main method is not relevant here. The scope in which you have declared the variables, however, is very important.

Have you walked through what happens in the first version of the code?

Create new instance of Overloads
  -> ov2 = Create new instance of Overloads
      -> ov2 = Create new instance of Overloads
         -> ov2 = Create new instance of Overloads

and so on. The variable ov2 is in scope of the class, thus it is initialized whenever an instance of the class is instantiated. This will never terminate until you run out of memory and get the stack overflow. Run it with a debugger for a clearer view.

The second version of the code only instantiates one instace of Overloads, in the scope of the main method. Thus creating one instance does not lead to the newly created instance creating new instance and so on..

Sign up to request clarification or add additional context in comments.

Comments

1

You can do like this

public class Overloads {
    String uniqueID;
    static Overloads ov2 = new Overloads();

    public static void main(String[] args) {
        System.out.println("IN MAIN");
    }

    public void setUniqueID(String theID) {
        // II lots of validation code, and then:
        uniqueID = theID;
        System.out.println(uniqueID);
    }
}

this will create shared instance of Overloads, instantiation will be done only once, when class loaded

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.