Search code examples
javaobjectconstructorexecutioncreation

Constructor code does not execute before object is created JAVA


I have recently played with code in java, and encountered this problem, that the code inside the constructor seems to be not executed, as the compiler throws the NullPointerException.

public class ObjectA {

protected static ObjectA oa;
private String message = "The message";

public ObjectA() {

    oa = new ObjectA();

}

public static void main(String args[]) {

    System.out.println(oa.message);

}  }

Now when i move the creation of the object before the constructor, i.e. I do it in one line, then everything works fine.

Can anyone explain to me why does this happen, and where my understanding of the code is wrong?

Thanks in advance.


Solution

  • You're never calling the ObjectA() constructor, except in the ObjectA constructor. If you ever did call the constructor (e.g. from main), you'd get a stack overflow because you'd be recursing forever.

    It's not really clear what you're trying to do or why you're using a static variable, but your code would be simpler as:

    public class ObjectA {
        private String message = "The message";
    
        public static void main(String[] args) {
            ObjectA oa = new ObjectA();
            System.out.println(oa.message);
        }
    }
    

    Also note that the compiler never throws an exception. It's very important to distinguish between compile-time errors (syntax errors etc) and execution-time errors (typically exceptions).