首页 > 编程语言 > 详细

Java Method Overriding --- runtime polymorphism ! not overloading

时间:2016-06-27 01:34:29      阅读:236      评论:0      收藏:0      [点我收藏+]
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

原文:http://www.cnblogs.com/morningdew/p/5618933.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!