Polymorphism in Overloaded and Overridden Methods

前端 未结 4 1940
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 03:51

Let\'s take this simple Java code:

public class Animal {
  public void eat() {
    System.out.println(\"Generic Animal Eating Generically\");
   }
}

public          


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 04:36

    This is happens because of method overriding. In method overriding, the reference type does not matter, it is the object type that matters. Animal ah is simply a reference to the object and the actual object is of type Horse. So, Horse's method will be called instead of reference type Animal's method.

提交回复
热议问题