Thursday, April 12, 2007

Overloading and Overridding

For long i thought , this is one of the simplest concept in java..
Both types of polymorphism have same method or function names .
In overriding , the function in the super class is over ridden by the subclasses and both have the same name , same parameters and same return types.

Over ridding example


class Animal
{
public void eat()
{
}
}

class Dog extends Animal
{
public void eat()//overriding eat of animal
{
}
public void befriendly()
{
}
}

public class Test
{
public static void main(String a[])
{
Animal a = new Dog();
a.eat()// dogs eat is called because at runtime a is an object if Dog.
a.befriendly();//Complier error.....
}
}

Remember
Animal a=new Dog (); means that the variable a is a animal reference variable at compile time and Dog's object during run time..
So, even though at runtime a.befriendly(); may run as a is a Dog's object , It will not compile because at compile time "a" is a animal reference.

In Overloading , the function in the same class or super class is overloaded whereby the functions have the same name and should have different number of parameters or different types of parameters and can have different return types.

Overloading Example

class Vehicle
{
public void parts(String part1)
{
}
}

class van extends Vehicle
{
public void parts(String head, String part1)// This is not over ridding the parts of the Vehicle class, it is overloading
{
}

public void parts(String head, String part1,String part2)
{
}
}

public class test2
{
public static void main(String a[])
{
Vehicle van = new van();
van.parts("asdfasd","fads");//compiler error
Van v= new Van();
v.parts("DF","Adsfa","Dfd");//legal
}
}

In here the Parts() of Vehicle is overloaded by parts of Van and not over ridden.
So when the compiler comes across
Vehicle van = new van();
It is Vehicles reference in the compile time , so
van.parts("asdfasd","fads");
results in a compiler error..
Though at run time it may seem perfect..

You should keep in mind that

= > The method to be overloaded is decided at compile time.
= > The method to be overridden is decided at run time.
= > You can run only after you have compiled..

No comments: