Thursday 25 September 2014

Session 11 :- Overriding

What is Overriding ?

  • Giving child specific implementation by keeping the same method definition which is defined as same as parent class is called as method overriding.
  • Overriding possible only in case of inheritance. 
  •  In case of overriding the method definition must be same as define in parent class that method name must be same, return type must be same, parameter must be same. 
  •   In case of method overriding access specifier must be same visibility or higher visibility. 
  •  We can achieve standardization in method name and also we can give child specific implementation. 
  • In case of overriding the parent copy will not be destroyed rather in child copy implement will different. 
  • Constructor can’t be overriding because it can’t be inherited .

Note:- It a good practice annotation while you use the overriding @ override.
 
Example :-overriding


public class Car {
   public void start(){
   System.out.println ("start manually:- parent class");

      }
               }
public class BmwCar extends Car {
  @Override
   public void start() {  
System.out.println("Auto start : Child specific  implementation ");
        }

      }
public class Driver { 
 public static void main(String[] args) {
          BmwCar bmw= new BmwCar();

          bmw.start();// call override method

     }

      }


OUTPUT:

     Auto start : Child specific implementation.



Example 17:-overriding :-



       public class Animal {
public void eat()
     {
 
System.out.println("Animal can eat........");
     }
public void run()
     {
System.out.println("Animal can run......");
     }
    }
public class Elephant extends Animal{
    @Override
public void eat() {
   System.out.println("Elephant can eat vegetable,");
     }
//override the parent class method
       @Override  public void run(){
 System.out.println("Elephant can’t run fast.....");
     }

  }
public class Tiger extends Animal{
@Override
public void eat() {
System.out.println("Tiger can eat non-veg...");
     }

     @Override
  public void run() {  System.out.println("Tiger can run fast...");
     }

}
public class Run {  public static void main(String[] args) { //create the child class object  and access the overridden method
      Tiger t=new Tiger();
t.eat();

t.run();
//create the child class object  and access the overridden method 
      Elephant e=new Elephant();
e.eat();

e.run();



OUTPUT:-
                     Tiger can eat non-veg...
               Tiger can run fast...
               Elephant can eat veg…
               Elephant can’t run...

Now Give me ans of following question.
  

Think: - Give name of the Inbuilt INTERFACE which is present in java API ??
Think:- Give name of the inbuilt Overload method which is present in java API ??
 
 

No comments:

Post a Comment