Monday, 8 May 2017

Method Overriding ~ mkniit

When a method in a sub class has same name and type signature as a method in its super class, then the method is known as overridden method. Method overriding is also referred to as runtime polymorphism. The key benefit of overriding is the abitility to define method that's specific to a particular subclass type.

Example of Method Overriding

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");
 }
}
As you can see here Dog class gives it own implementation of eat() method. Method must have same name and same type signature.
NOTE : Static methods cannot be overridden because, a static method is bounded with class where as instance method is bounded with object.

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 original method inside the super class. This is the only way by which method can be overriden by changing its return type.
Example :
class Animal
{
 Animal myType()
 {
  return new Animal();
 }
}

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

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).
difference between overloading and overriding

Q. Can we Override static method ? Explain with reasons ?

No, we cannot override static method. Because static method is bound to class whereas method overriding is associated with object i.e at runtime.

No comments:

Post a Comment