Tuesday, 26 April 2011

The Difference Between Method Overloading and Method Overriding

When taking the Oracle Certified Professional, Java SE 6 Programmer exam, one of the tricks used to try to catch you out is to try to confuse you over the meanings of overriding and overloading methods and I guess that this is because they have similar sounding names. This blog clarifies all that - take a look at the code...

/**
 * Class that demonstrates Overloading of methods. myMethod() has been overloaded three
 * times...
 */
public class OverloadExample {

 
public void myMethod() {
   
System.out.println("Blank");
 
}

 
public void myMethod(String str) {
   
System.out.println("Input is: " + str);
 
}

 
public void myMethod(int arg) {
   
System.out.println("Value is: " + arg);
 
}

 
public void myMethod(double arg) {
   
System.out.println("Value is: " + arg);
 
}

 
public static void main(String[] args) {

   
OverloadExample example = new OverloadExample();
    example.myMethod
();
    example.myMethod
("Hello");
    example.myMethod
(42);
    example.myMethod
(23.3);
 
}
}

The code above demonstrates overloading, whilst the code below demonstrates overriding:

/**
 * Class that demonstrates Overriding of methods. myMethod() has been overridden twice...
 */
public class OverrideExample extends OverloadExample {

 
@Override
 
public void myMethod(String str) {
   
System.out.println("New input is: " + str);
 
}

 
@Override
 
public void myMethod(int arg) {
   
System.out.println("New value is: " + arg);
 
}

 
public static void main(String[] args) {
   
OverrideExample example = new OverrideExample();
    example.myMethod
();
    example.myMethod
("Hello");
    example.myMethod
(42);
    example.myMethod
(23.3);
 
}
}

The only tip here is to read the question carefully: overloading is not overriding they just sound similar.

2 comments:

Joseph Ndungu said...

Thanks a bunch...simple,precise understandable explanation!!!

Javin Paul said...

Indeed very good blog, clean and precise.By the way I have also shared some rules of method overloading and overriding in Java, which complements your blog post.

Thanks
Javin