Java Method Overriding --- runtime polymorphism ! not overloading

Posted morningdew

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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).                                                                                             

      

 

以上是关于Java Method Overriding --- runtime polymorphism ! not overloading的主要内容,如果未能解决你的问题,请参考以下文章

Java 重写(Overriding)和重载(Overloading)

Java中的方法覆盖(Overriding)和方法重载(Overloading)是什么意思?

Java中的方法覆盖(Overriding)和方法重载(Overloading)是啥意思?

java多态怎么解释?

Java中重载(Overload)和重写(Override)的定义

java语言中,overload(重载)和override(覆盖)有何区别?