Will instances inside an instance get null'ed when the main instance is null'ed

Let's say we have this code:

public class c1 {
    c2 secondclass = new c2();
}

public class c2 {
    public c2() {
        System.out.println("c2 instance created");
    }
}

If I set the c1 = null will the class c2 inside c1 get automatically null'ed? or do I need:

c1.c2 = null;
c1 = null;
Jon Skeet
people
quotationmark

No, it won't. It's important to understand that you never set an instance to null - you just set the value of a variable to null. There can be multiple variables with references to the same instance. It's hard to comment on your exact example as you appear to be using class names as variable names, but if you have:

public class Foo {
    // Note that good code almost never has public fields; this is for demo purposes only
    public Bar bar;
}

public class Bar {
    @Override public String toString() {
        return "Message";
    }
}

You can then do:

Foo foo1 = new Foo();
Foo foo2 = foo1;
// The values of foo1 and foo2 are now the same: they are references to the same object
foo1.bar = new Bar();
System.out.println(foo2.bar); // Prints Message
foo2 = null;
System.out.println(foo2); // Prints null
System.out.println(foo1.bar); // Still prints Message

Changing the value of foo2 to null makes no difference to foo1 - it doesn't change the value of foo1, nor does it make any difference to the object that the value of foo1 refers to.

In general, you need to be really, really clear about the differences between objects, variables and references. Once you've got that mental model straight, a lot of other things become much easier to understand.

people

See more on this question at Stackoverflow