In Java, an Object
can have a runtime type (which is what it was created as) and a casted type (the type you have casted it to be).
I'm wondering what are the proper name for these types. For instance
class A {
}
class B extends A {
}
A a = new B();
a was created as a B
however it was declared as an A
. What is the proper way of referring to the type of a
using each perspective?
The type of the variable
a
isA
. There's no changing that, since it's a reference. It happens to refer to an object of typeB
. While you're referring to thatB
object through anA
reference you can only treat it as though it were of typeA
.You can later cast it to its more specific type
and use the
B
methods on that object.I would say that you differentiate between the type of the variable/reference and the type of the object. In the case
the variable/reference would be of type
A
but the object of typeB
.The terminology you are looking for is the Apparent Type and the Actual Type.
The Apparent Type is A because the compiler only knows that the object is of type A. As such at this time you cannot reference any of the B specific methods.
The Actual Type is B. You are allowed to cast the object (that is change its apparent type) in order to access the B specific methods.
To determine
a
is object of which class you can use:In this case,
A
is the reference type whileB
is the instance typeThe Java Language Specification speaks about a variable's declared type, the javadoc of
getClass()
about an object's runtime class.Note that there is no such thing as a runtime type in Java;
List<String>
andList<Integer>
are different types, but their instances share the same runtime class.