Java术语,用于区分运行时类型与编译时类型

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 while B is the instance type

点赞
评论
Eliv
Eliv

The 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> and List<Integer> are different types, but their instances share the same runtime class.

点赞
评论
sut
sut

我认为,区分对象(存在于执行时,只是具有执行时间类型)和具有编译时类型的表达式(例如变量)之间是很重要的。

因此,在这种情况下:

A a = new B();

a is a variable, of type A. Its value at execution time is a reference to an object of type B.

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.

点赞
评论
xiste
xiste

您正在寻找的术语是表观类型和实际类型。

A a = new B();

表观类型为A,因为编译器仅知道该对象的类型为A。因此,此时您不能引用B的任何特定方法。

实际类型为B。允许访问该对象(即更改其外观类型)以访问B特定方法。

点赞
评论
自大狂
自大狂

The type of the variable a is A. There's no changing that, since it's a reference. It happens to refer to an object of type B. While you're referring to that B object through an A reference you can only treat it as though it were of type A.

您以后可以将其转换为更具体的类型

B b = (B)a;

and use the B methods on that object.

点赞
评论
iut
iut

我要说的是,您要区分变量/引用的类型和对象的类型。在这种情况下

A a = new B();

the variable/reference would be of type A but the object of type B.

点赞
评论
滚好么
滚好么

To determine a is object of which class you can use:

/*The java.lang.Object.getClass() method returns the runtime class of an object*/   
System.out.println("a is object of: "+a.getClass());
点赞
评论
思密达
思密达

Section 15.5. Expressions and Run-Time Checks differentiates between

  • 表达式的类型
  • 被引用对象的类

例如,

If the type of an expression is a reference type, then the class of the referenced object, or even whether the value is a reference to an object rather than null, is not necessarily known at compile time. There are a few places in the Java programming language where the actual class of a referenced object affects program execution in a manner that cannot be deduced from the type of the expression...

[snip]

An expression whose type is a reference type may be tested using instanceof to find out whether the class of the object referenced by the run-time value of the expression

因此,将上述语言应用于

A a = new B();

我们可能会说类似

The static type of the expression a is A, despite the fact the value stored in a is a reference to the object of runtime class B.

我个人以以下方式解释这两个概念(但是请注意,我不确定其正确性):

  • 表达式的静态类型是纯粹的语法概念,在编译时存在于源代码中,以供Java编译器处理
  • 对象的运行时类是运行时内存中存在的实际机器构造,以供Java虚拟机进行处理
点赞
评论