0

I have an object, obj, of type MyObject, that I declare an instance of.

MyObject obj;

However, I don't initialize it. MyObject's Class looks something like:

public class MyObject {
    public String i;
    public String j;
    public MyObject(String i) {
        i = this.i;
    }
}

So now, I want to set the value of j. So I say:

obj.j = "Hello";

Can I do this without having initialized obj? i.e. without saying:

obj = new MyObject("My i");

Will this object be null if I were to check the value of it, if I don't initialize it, or is setting a field within it enough to make it not null?

Thanks!

1
  • Your constructor statement is backwards. It should say this.i = i; Commented Nov 20, 2013 at 16:30

1 Answer 1

3

No, you cannot do that. You will have to create a new instance of MyObject if you want to access its fields.

Unless you make the fields static, ofcourse.

Do note that having your fields public violates encapsulation. You should make them private (or protected, if it's appropriate) and use getters and setters to provide access.

Sidenote:

public MyObject(String i) {
    i = this.i;
}

This will not do what you want.

You have to assign the parameter i to the field variable i, not the other way around.

public MyObject(String i) {
    this.i = i;
}
Sign up to request clarification or add additional context in comments.

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.