質問

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.

役に立ちましたか?

解決

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

他のヒント

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.

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.

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.

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());
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top