-2

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.

MT0
  • 143,790
  • 11
  • 59
  • 117
Shaun Mbhiza
  • 1
  • 1
  • 1
  • Why should it print "true"? `b` refers to the object created by `new C()`. I don't think that the certification process will work, if you don't even understand these basics. – Tom Jul 13 '16 at 08:15

3 Answers3

1

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.

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

It is very normal that it will print false because b has been already initilized with the reference of the object a, even if they reset the a to null after that but b will keep always the reference of the object

Anas EL KORCHI
  • 2,008
  • 18
  • 25
0

When you create an object in Java using new, it is allocating space in memory for it and sets your a to the point in memory where your object is located.

a is not the object itself, it is a pointer to the location of your object in memory

A a = new C(); 
// a points to the location of your new C

B b =(B)a; 
// now b also points to that location

C c =(C)a; 
// same goes for c

a = null; 
// a now points to null, but b and c still point to the old location

Think of it almost like int types. If you assign one int to another int, these two variables aren't "linked" -- instead the actual value is being copied (in the case of pointers / references: the location of the object in memory) from one to another

nihab
  • 56
  • 4