Why reference variable of type object must be cast when used as other object type

前端 未结 4 1201
一向
一向 2021-01-03 12:08

Although all classes in Java are sub-classes of Object class, but different from other object types, a reference variable of type Object can\'t be assigned to any other refe

4条回答
  •  长发绾君心
    2021-01-03 12:39

    Given the statement: Object o = new Tiger();

    The type of the variable (Object) controls the interactions (methods) available to you while the type of the value (Tiger) controls the behavior that is executed for a given interaction.

    By using an Object reference for a Tiger instance as in this example, you're saying that you want to use an instance of Tiger as an Object. Well, an object doesn't have the method Scream() so it's not going to give you that option. If you want to be able to Scream(), use it as a type that actually knows how to Scream() like Animal or Mammal

    btw, methods should start with a lowercase

提交回复
热议问题