Tuesday, June 10, 2014

# 16 - RIDE it OVER to OVERRIDE

Hello,

Many of us have heard about Overriding and Overloading concepts in Java. I still get confused whenever I face this question in interviews..:P So I thought of clearing mine and your confusion about them in the coming posts by disussing about these topics in detail.! :D

This post is all about Overriding and in the next post we will see Overloading and their difference. There are many differences between each other but still the beginner’s gets confused in understanding these concepts. So I thought of trying my part to make it easy in understanding..:P

The overloading and overriding concepts apply only to methods. Whenever you hear people using these words, you can be sure that there are planning to do something with methods.

Just to repeat, this post is completely dedicated to readers. (I know it is
a bad joke..:P)
This post is completely dedicated to Overriding..!

Overriding –This word can also be divided into OVER and RIDE. Yes. We are gonna go for a ride on the methods..!





OVER-RIDDEN Methods

The overriding concept is related to 2 excellent features in Java – Inheritance and Polymorphism
Had there been no inheritance concept, there wouldn’t have been overriding concept. So burn this in your head that overriding can happen only when Inheritance is there. And regarding Polymorphism, we will see about in few seconds.
//class Animal
public class Animal { 

 public void eat(){
  System.out.println("Animals eat grass");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // OVERRIDDEN method 'coz eat() already exists in Animal (parent) class
 public void eat(){
  System.out.println("Horses eat grass and oats");
  // add Horse related code
 }
}
In the above program, you can see that we use the extends which says that there is a Inheritance concept and the parent class has a method eat() which says "all animals eat grass". But I have a subclass Horse which is also an animal but eats grass and oats as well. In this case, I want to define my own specifications for Horse. That’s where the overriding concept comes into the picture. So I have overridden the existing eat() method to the subclass Horse and implemented in my own way. Simple..!

Then here comes other excellent feature of Java – Polymorphism.
Poly – many
Morph – forms.
In other words, an object appearing in different forms is called Polymorphism. Let’s see what it has to do with overriding.
public class TestAnimal{
 public static void main(String... x){
  Animal a = new Animal();
  Horse h  = new Horse();
  
  a.eat(); // prints animal eat()
  h.eat(); // prints horse eat()
  
  //polymorphism comes here
  Animal an = new Horse();
  an.eat(); // which eat method will invoke ?
  
  // this statement gives compile error
  //Horse hr = new Animal();
  
 }
}

//class Animal
class Animal { 

 public void eat(){
  System.out.println("Animal.eat()");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // OVERRIDDEN method 'coz eat() already exists in Animal (parent) class
 public void eat(){
  System.out.println("Horse.eat()");
  // add Horse related code
 }
 
 public void run(){
  System.out.println("Horse.run()");
 } 
}
I know this will be a confusing one but I try my best to make it simple and easy. So to sum up the above program, I have created 2 objects,
Animal a = new Animal();
Horse h  = new Horse();
Using Animal object I can invoke 1 method ie., a.eat()
Using Horse object I can invoke 2 methods ie., h.eat() and h.run()

Now the interesting part comes here,
Animal an = new Horse();
How many methods can I call using "an" ?

Well, first analyze the above statement. new Horse() means object of Horse class and the reference is Animal. So we are assigning the horse object to an Animal reference. It is legal coz Horse is a subclass of Animal class.
As we have assigned it to an Animal reference, the compiler assumes that it is an animal object. The Animal has only one method – eat(). So if we try to invoke run() method using “an”, you get a compiler saying “The method run is undefined for the type Animal”.

Now if I call an.eat() method, which eat method will be invoked ? As the compiler assumes that "an" is an animal object hence it calls animal eat() method ??

The answer is NO.

The Horse eat() method will be invoked and hence we get the output as,

Horse.eat()

Let me explain why it happens. Just now I said that the compiler assumes "an" object as Animal object. But at runtime, it will realize that it is a Horse object which is assigned to Animal reference. Hence it will call Horse eat() method. Compiler assuming at compile time and realizing the actual object at runtime is called Dynamic Binding or Runtime Polymorphism.

Here are the rules with Overriding.
  • The argument list MUST exactly match the overridden method.
//class Animal
class Animal { 

 public void eat(String food){
  System.out.println("Animal.eat()");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // OVERRIDDEN method 'coz eat(food) already exists in Animal (parent) class
 public void eat(String food){
  System.out.println("Horse.eat(food)");
  // add Horse related code
 }
 
 // This is NOT overridden method coz arguments doesn't match
 // This is just like any other method in a class.
 public void eat(String food, String water){
  System.out.println("Horse.eat(food, water)");
 } 
}
  • The return type must be same or subtype of the return type declared in the parent class.
//class Animal
class Animal { 

 public void eat(String food){
  System.out.println("Animal.eat()");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // This method gives copile time error saying "The return type is incompatible with Animal.eat(String)"
 // coz the return types are different 
 public int eat(String food){
  int i = 3;
  System.out.println("Horse.eat(food)");
  return i;
 } 
}
  • The access level cannot be more restrictive but can be same or less restrictive than the overridden method.
//class Animal
class Animal { 
 
 // this method is with public access
 public void eat(String food){
  System.out.println("Animal.eat()");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // This method throws the compile time error saying "Cannot reduce the visibility of the inherited method from Animal"
 // The overriding method canNOT reduce its visibility (public to private is reducing its visibility)
 private void eat(String food){
  System.out.println("Horse.eat(food)");
  // add Horse related code
 } 
}
  • The overriding method must NOT throw checked exceptions that are broader than those declared by the overridden method but it can throw narrower exceptions.
    • A method that declares a FileNotFoundException cannot be overridden by a method that declares SQLException, Exception or any other checked exception unless it is a subclass of FileNotFoundException.
//class Animal
class Animal { 
 
 // this method is with public access
 public void eat(String food) throws FileNotFoundException{
  System.out.println("Animal.eat()");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // This method throws the compile time error saying "Exception Exception is not compatible with throws clause in Animal.eat(String)"
 // The overriding method canNOT throw broader exceptions than those declared in the overridden method.
 // This method can throw FileNotFoundException or its subclass exceptions.
 // It is completely legal if this method doesn't throw any Exception
 public void eat(String food) throws Exception{
  System.out.println("Horse.eat(food)");
  // add Horse related code
 } 
}
  • We canNOT override final and static methods. 
//class Animal
class Animal { 
 
 // this method marked final, so canNOT override
 public final void eat(String food){
  System.out.println("Animal.eat()");
 }
 
 // this method marked static, so canNOT override
 public static void run(){
  System.out.println("Animal.eat()");
 }
}
// class Horse - subclass of Animal
class Horse extends Animal{
 
 // trying to override final eat(food), 
 //we get compile time error saying "Cannot override the final method from Animal"
 public void eat(String food){
  System.out.println("Horse.eat(food)");
  // add Horse related code
 }
 
 // trying to override static run(), 
 //we get compile time error saying "This instance method cannot override the static method from Animal"
 public void run(){
  System.out.println("Horse.run()");
 }
}


That's all with the Overriding concept. The Overloading concept is much easier to explain and to understand. Till then enjoy a ride with Overridden methods.!

Thanks :)