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).
我想知道这些类型的专有名称是什么。例如
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?
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.我认为,区分对象(存在于执行时,只是具有执行时间类型)和具有编译时类型的表达式(例如变量)之间是很重要的。
因此,在这种情况下:
a
is a variable, of typeA
. Its value at execution time is a reference to an object of typeB
.The Java language specification uses "run-time class" (e.g. for the purpose of overriding, as in section 15.12.4.4) for the type of an object. Elsewhere I think it just uses "type" for the type of an expression, meaning the compile-time type.
您正在寻找的术语是表观类型和实际类型。
表观类型为A,因为编译器仅知道该对象的类型为A。因此,此时您不能引用B的任何特定方法。
实际类型为B。允许访问该对象(即更改其外观类型)以访问B特定方法。
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
.您以后可以将其转换为更具体的类型
and use the
B
methods on that object.我要说的是,您要区分变量/引用的类型和对象的类型。在这种情况下
the variable/reference would be of type
A
but the object of typeB
.To determine
a
is object of which class you can use:Section 15.5. Expressions and Run-Time Checks differentiates between
例如,
因此,将上述语言应用于
我们可能会说类似
我个人以以下方式解释这两个概念(但是请注意,我不确定其正确性):