Yakuman
Yakuman

Reputation: 183

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.

Upvotes: 0

Views: 1171

Answers (5)

vels4j
vels4j

Reputation: 11298

Hope something you need like this

public class ObjectA {

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

    public ObjectA() {
    }

    public static ObjectA getInstance() {
        if (oa == null) {
            oa = new ObjectA();
        }
        return oa;
    }

    public String getMessage() {
        return message;
    }

    public static void main(String args[]) {
        System.out.println(ObjectA.getInstance().getMessage());
    }
}

Upvotes: 0

tk66
tk66

Reputation: 284

1) You never create an object

put:

ObjectA oa = new ObjectA();

in your main before your System.out.print.

2) set the message to public instead of private.

Upvotes: 0

Qwerky
Qwerky

Reputation: 18445

You define a static variable oa but you only ever intialise it in the class's constructor. You never instantiate your class ObjectA so oa can only ever be null.

When you call your main method it tries to access the message variable of a null object, hence the NPE.

Upvotes: 0

ktm5124
ktm5124

Reputation: 12123

You need to move ObjectA oa = new ObjectA() to your main method.

Also, there is no need for this: protected static ObjectA oa;

You should copy/paste a Hello World program from a tutorial and see how it works.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500675

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).

Upvotes: 7

Related Questions