Overloading and Overrriding – revisited


Overloading

is applied only within a class by simply

  1. having the same name for the method but
  2. passing different parameters list

what can happen in Overloading is that

  • the number of arguments to the method can change
  • the same name with different parameter list can be defined in the super class also

what cannot happen in Overloading is that

  • same name and same no of arguments as the compiler does the differentiation using only the method signatures that comprises of method name and the arguments passed
  • same name with different return type cannot qualify and throws compile time error as ‘the Duplicate method defined’ for the same reason as above

example

 //Allowed
 public int display(){
 System.out.println("returning int");
 return 0;
 }
 //Allowed
 public int display(int a)throws IOException{
 System.out.println("returning int with a");
 return 0;
 }

 //Allowed
 public int display(int a,int b){
 System.out.println("returning int with a and b");
 return 0;
 }

 //Allowed
 public int display(char a) throws IOException{
 System.out.println("returning int with char a");
 return 0;
 }

 //Allowed
 public int display(String a) throws IOException{
 System.out.println("returning int with char a");
 return 0;
 }

 //Not Allowed - Duplicate method
 public int display(char a) throws IOException{
 System.out.println("returning int with char a");
 return 0;
 }

 //Not Allowed - Duplicate method
 public String display(char a) throws IOException{
 System.out.println("returning int with char a");
 return "hi";
 }

use Overloading only if the method does the same logic with different parameters

Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods—they are new methods, unique to the subclass

Overriding

is applied only when the sub class tends to modify the behavior of a method in the super class

  1. having the same name for the method
  2. having the same parameter list
  3. having the same return type

what can happen in Overriding is that

1. the access modifier can be less restrictive than the one in super class

  • if the superclass method is public, the overriding method must be public
  • if the superclass method is protected, the overriding method may be protected or public
  • if the superclass method is package, the overriding method may be package, protected, or public
  • if the superclass methods is private, it is not inherited and overriding is not an issue

2. the overriding method in the subclass class cannot throw any exception that is broader than the exception thrown by the super class

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s