Explain Overloading and Overriding methods with example

Overloading :

In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. This methods are said to be
overloaded and the process is referred to as method overloading.

Overloaded methods must differ in the type and/or number of parameters.

The return type alone is insufficient to distinguish two versions of a method.

Example :
Class A
{
void disp()
{
System.out.println(“No parameters”);
}
void disp(int a)
{
System.out.println(“a: “+a);
}
void disp(int a, int b)
{
System.out.println(“a and b: “+a+” “+b);
}
Void disp(double a)
{
System.out.println(a);
}
class Overload
{
public static void main(String args[])
{
A ob = new A();
ob.disp();
ob.disp(10);
ob.disp(10, 20);
ob.disp(123.25);
}
}
Output :
No parameters
a: 10
a and b: 10 20
double a: 123.25

                                                                Overriding :

In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass.

When an overridden method is called from within a subclass, it will always refer to the
version of that method defined by the subclass. The version of the method defined by the
superclass will be hidden. 

 If we need to access the superclass version of an overridden function, we can do so by using
super keyword which is resolved at compile time. Dynamic method dispatch is the
mechanism by which a call to an overridden method is resolved at run time, rather than compile
time.

Example :
class A
{
void show()
{
System.out.println("SUPER A”);
}
}
class B extends A
{
void show()
{
System.out.println("SUB B”);
}
}
class C extends A
{
void show()
{
super.show(); // this calls A's show()
System.out.println("SUB C”);
}
}
class Override
{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B();
C c = new C();
b.show(); // this calls show() in B
c.show(); // this calls show() in C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.show(); // calls A's version of show()
r = b; // r refers to a B object
r.show(); // calls B's version of show()E
}
}
Output :
SUB B // by overriding method
SUPER A // solved by super key word
SUB C
SUPER A // by using run time polymorphism
SUB B // by using run time polymorphism

Comments