Monday, March 23, 2015

Method Overriding Definition, Advantages , Disadvantages , Example.

 Method Overriding


v  Definition:-


ð Defining a method in the subclass that has the same name, same arguments and same return type as a method in the super class and it hides the super class method  is called method overriding.

ð Static method cannot be overridden because It can be proved by runtime polymorphism


v  Advantage of Method Overriding:-

ð Method Overriding is used to provide specific implementation of a method that is already provided by its super class.
ð Method Overriding is used for Runtime Polymorphism


v  Rules for Method Overriding:-

ð Method must have same name as in the parent class

ð Method must have same parameter as in the parent class.

v  Understanding the problem without method overriding:-


ð Let’s understand the problem that we may face in the program if we don’t use method overriding.

class Vehicle
{
void run()
{
System .out. println(“Vehicle is running”);
}
}
class Bike extends Vehicle
{
Public static void main(String args[])
{       
Bike obj = new Bike();
obj.run();
}
}


Ø  Output: - Vehicle is running


Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.


v  Example of method overriding:-



class Vehicle
{
void run()
{
System.out.println(”Vehicle is running”);
}
}
class Bike extends Vehicle
{
          void run()
{
System.out.println(“Bike is running safely”);
}
public static void main(Stnng args[])
{
Bike obj = new Bike();
obj.run();
                   }
          }

Ø  Output: - Bike is running safely



 In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.

2 comments: