Difference between Dynamic and Static type assignments in Java

前端 未结 5 968
孤独总比滥情好
孤独总比滥情好 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条回答
  •  萌比男神i
    2020-12-03 02:55

    The concrete, runtime type of f is Fruit (as you correctly stated in your question).

    So Beta b = f; initilalizes a variable whose declared, compile-time type is Beta, and whose runtime type is Fruit. This won't compile though, because the compile-time type of f is Fruit, and Fruit is not a subclass of Beta, so f can't be assigned to a variable of type Beta.

    In a = b;, b, whose runtime type is Fruit (see above) is assigned to the variable a, declared as Alpha a. So a's compile-time type is Alpha and its runtime type is Fruit.

提交回复
热议问题