Reference Variable Data Type (Java)

I have a question for referencing variables. My question is, does the type of the declared variable refer to the type of the object or to the type of the link that is stored in it?

I found a very interesting answer by Edwin Dalorzo about this topic. It describes that each link has a type, and when we perform type casting, it only changes the type of link used to refer to this object (and not the type of this object itself!).

So my question is whether the type of the reference variable indicates the type of link in it. Of course, the type of the object and the type of link are the same.

Suppose B a = new B();

B is currently telling the compiler that the bindings are of type B?

Or does the compiler completely ignore the type of data that is stored in it (link), and only think about the type of the underlying object? The same goes for the type of the return method.

+4
source share
2 answers

A link has a type and can only have a link assigned to it by an object that is an instance of this type (or a subclass or implementation class)

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

There are situations when only one question, for example,

Thread t = null;
t.yield();

In this case, the static method is called and the actual value of the link is not considered.

Conversely, when using reflection, where the type of link is not important, only the main object.

+4
source

When the compiler sees this line:

B a = new B();

he will only "know" the following:

  • a is not null
  • a " " B

:

Object o = "hello";

, o , "" . "" ( , , ). javac, java - "" .

: Java "" - JIT. "" ( ).

+2

Source: https://habr.com/ru/post/1683038/


All Articles