4

I have a question to reference variables. My question is whether the type of a declared variable refers to the type of the Object or to the type of the reference which is stored in it?

I found a very interesting answer of Edwin Dalorzo on this topic. He describes that every reference has a type and when we perform a typecast it does only change the type of the reference used to refer to that object (not the type of that object itself!).

So my question is whether the type of a reference variable tells us which type of reference is stored in it. Of course the type of the Object and the type of the reference are the same.

Suppose B a = new B();

Does B now tell the compiler that a holds references of type B?

Or does the compiler completely ignore the type of the data that is stored in it (the reference) and only thinks of the type of the underlying object? Same for method return type.

GhostCat
  • 137,827
  • 25
  • 176
  • 248

2 Answers2

4

The reference has a type, and it can only have a reference assigned to it an object which is an instance of that type (or a sub-class or implementing class)

The compiler and the JVM checks both the reference and the type of the object.

There is situations where only one matters e.g.

Thread t = null;
t.yield();

In this case a static method is called, and actual value of the reference isn't considered.

Conversely, when using reflection, where the type of the reference isn't important, only the underlying object.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

When the compiler sees this line:

B a = new B();

it will "only" know the following things afterwards:

  • a is not null
  • a has "at least" type B

Like in:

Object o = "hello";

The compiler does not know later on that o is in fact a String, and not "just" an Object. Theoretically the compiler could "remember" that additional part as well (to a certain degree, for example within the scope of a method). But javac, the java to bytecode compiler is pretty conservative about such "sophisticated" data flow considerations.

Keep in mind: the Java approach to "performance" is to emphasize runtime optimizations by the JIT compiler. In that sense it is simply not "worth" spending a lot of efforts regarding extended compile time analysis (excluding type inference).

GhostCat
  • 137,827
  • 25
  • 176
  • 248