0

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;
Community
  • 143
  • 2
  • 10
  • 1
    What stops you from testing it? – Pshemo Nov 08 '15 at 17:09
  • I can't test it because if I set c1 to null I can't System.out.println(c1.c2); – Community Nov 08 '15 at 17:13
  • @Danielngx-development If you have another reference to the object then you can test it. If you don't, then it doesn't matter what happens inside the object, because there's no way for it to impact the program. – resueman Nov 08 '15 at 17:14
  • Create second reference of type `c1` which will hold same object. Like `c1 mainRef = new c1(); c1 secondRef = mainRef; mainRef = null;`. Since they both hold same object you will be able to see `c2` from other reference. – Pshemo Nov 08 '15 at 17:14
  • @Danielngx-development: It really helps if you have a complete example, instead of one where you're referring to classes as if they're variables. – Jon Skeet Nov 08 '15 at 17:15

1 Answers1

2

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.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194