Java, terminology clarification

左心房为你撑大大i 提交于 2019-11-30 16:32:04
Jon Skeet

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.

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.

In this case, A is the reference type while B is the instance type

I would say that you differentiate between the type of the variable/reference and the type of the object. In the case

A a = new B();

the variable/reference would be of type A but the object of type 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.

You can later cast it to its more specific type

B b = (B)a;

and use the B methods on that object.

The terminology you are looking for is the Apparent Type and the Actual Type.

A a = new B();

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:

/*The java.lang.Object.getClass() method returns the runtime class of an object*/   
System.out.println("a is object of: "+a.getClass());
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!