I am currently in the process of obtaining my Oracle certification and this is one of the concepts that I am failing to grasp. The following code snippet does not print true even though I expect it to:
interface I {
}
class A implements I{
}
class B extends A{
}
class C extends B{
}
public class Test {
public static void main(String... args) {
A a = new C();
B b =(B)a;
C c =(C)a;
a = null;
System.out.println(b==null);
}
}
Why do I expect a true? b was created using a and a has now been set to null.
b was created using a and a has now been set to null.
You've misunderstood what this line does:
B b =(B)a;
That copies the current value of a
as the initial value of b
. That's all it does. The two variables are then entirely independent. Changing the value of a
does not change the value of b
. Yes, while they happen to refer to the same object, any changes to that object will be visible via either variable, but the variables themselves are not tied together.
One thing that may be confusing you is what the value of the variable is - it's just a reference. See this answer for the difference between variables, references and objects.
See more on this question at Stackoverflow