Saturday, April 20, 2013

Q : Difference between Overloading and overriding ?

Ans: The Major difference between overloading and overriding :

In overriding the method being written with same name has the same :
1.Paramter
2.return type
3.And cannot have broader exception than that of the superclass.
 
whereas,

In overloading the method has the
1. different parameter's
2.different return types.
3.And may have different exception's

The major difference is when an overridden method is invoked the compiler observes the which object is invoking that particular method rather than the reference, And in the overloading the reference invoking the method matter's.

Let's take an example,

public class A {

public void run(){
 System.out.println("This is A's method");
        }
}

public class B extends A{

public void run(){
 System.out.println("This is A's method");
        }

public void run(String s){
 System.out.println("This is "+s+" method");
        }

}

 Now Output:
A a = new A();
a.run();

This is A's Method

B b = new B();
b.run();

This is B's Method

A a = new B();
a.run();
Its an Overriding
This is B's Method


B b = new B();
b.run("hi");
Its an overloading
B's Method is called

A a = new B();
a.run("hi")
Compiler error coz overloading works on the reference type

A a = new A();
a.run("hi");
Compiler error
A class doesn't have this method