• Java Method Overriding --- runtime polymorphism ! not overloading


    ref: http://www.studytonight.com/java/method-overriding-in-java.php                    

    Method Overriding between parent and child

    The key benefit of overriding is the ability to define method that's specific to a particular subclass type

    class Animal
    {
     public void eat()
     {
      System.out.println("Generic Animal eating");
     }
    }
    
    class Dog extends Animal
    {
     public void eat()   //eat() method overriden by Dog class.
     {
      System.out.println("Dog eat meat");
     }
    }

    The subclass will implement the method again. As the example shows. the Dog clss gives its own implementation of eat(). Method must have the same signature

    Static method cannot be overriden.

    Covariant return type

    Since Java 5, it is possible to override a method by changing its return type, If subclass override any method by changing the return type of super class method,

    then the return type of overriden method must be subtype of return type declared in origin method inside the super class. this is the only way by which method can be overriden by chancing its return type.

    class Animal
    {
     Animal myType()
     {
      return new Animal();
     }
    }
    
    class Dog extends Animal
    {
     Dog myType()     //Legal override after Java5 onward
     {
      return new Dog();
     }
    }


    Dog is a sub type of animal, therefore different return type is ok here

    Difference between Overloading and Overriding           

    Method OverloadingMethod Overriding
    Parameter must be different and name must be same. Both name and parameter must be same.
    Compile time polymorphism. Runtime polymorphism.
    Increase readability of code. Increase reusability of code.
    Access specifier can be changed. Access specifier most not be more restrictive than original method(can be less restrictive).                                                                                             

          

  • 相关阅读:
    智能家居项目(3):编译工具makefile
    9、Cocos2dx 3.0游戏开发找小三之工厂方法模式与对象传值
    Redis于windows在安装
    Gray Code -- LeetCode
    hdu 1575 Tr A(矩阵高速电源输入)
    phpstorm快捷键
    Reverse Linked List II -- LeetCode
    程序猿的故事-注定奉献给节目
    poj2112 Optimal Milking --- 最大流量,二分法
    POJ 3356 AGTC(最长公共子)
  • 原文地址:https://www.cnblogs.com/morningdew/p/5618933.html
Copyright © 2020-2023  润新知