Difference between Dynamic and Static type assignments in Java

前端 未结 5 970
孤独总比滥情好
孤独总比滥情好 2020-12-03 02:21

Given the follow class hierarchy what are the dynamic and static types for the following statements?

Class hierarchy:

class Alpha {}         


        
5条回答
  •  情歌与酒
    2020-12-03 02:33

    the dynamic and static types for the following statements

    Erm, a statement doesn't have a type, at least there is no such notion in the Java Language Specification. The spec does define two different kinds of types: the declared type of variable, field, or parameter, and the runtime class of an object.

    As the name indicates, the declared type of a variable, field or parameter is the type you mention in the declaration. For instance, the declaration Foo bar; declares a variable named bar of type Foo.

    The runtime class of an object is determined by the class instance or array creation expression used to construct it, and remains the same throughout the lifetime of that object.

    So the code:

    Integer i = 1;
    Number n = i;
    Object o = n;
    

    declares 3 variables of types Integer, Number and Object, respectively, all of which refer to a single object with runtime class Integer.

提交回复
热议问题