Java terminology for differentiating runtime type from compile-time type

前端 未结 8 1710
孤街浪徒
孤街浪徒 2020-12-06 08:56

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

8条回答
  •  清歌不尽
    2020-12-06 09:29

    Section 15.5. Expressions and Run-Time Checks differentiates between

    • the type of an expression
    • the class of the referenced object

    For example,

    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

    Hence, applying the above language to

    A a = new B();
    

    we might say something like

    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.

    Personally, I interpret the two concepts in the following manner (but beware I am unsure of its correctness):

    • static type of the expression is purely syntactic concept existing in source code at compile time for processing by Java compiler
    • runtime class of the object is actual machine construct existing in machine memory at runtime for processing by Java Virtual Machine

提交回复
热议问题