Java, terminology clarification

2019-02-11 07:39发布

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?

7条回答
欢心
2楼-- · 2019-02-11 08:16

I think it's important to distinguish between the object (which exists at execution time, and just has its execution time type) and an expression (such as a variable) which has a compile-time type.

So in this case:

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.

查看更多
登录 后发表回答