zoukankan      html  css  js  c++  java
  • 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).                                                                                             

          

  • 相关阅读:
    使用js来执行全屏
    vue多个组件的过渡
    mac笔记本上的工具
    webpack优化技术参考
    VS Code 编译器的调试工具整理
    自定义滑块Vue组件
    Multi-level Multi-select plugin
    cucumber learning : http://www.cnblogs.com/puresoul/category/340832.html
    Opensuse enable sound and mic card
    Shell displays color output
  • 原文地址:https://www.cnblogs.com/morningdew/p/5618933.html
Copyright © 2011-2022 走看看