Learn Overloading in Java


Overloading is defining more than one set of statement with same name but different signature. Method overloading means  to have two or more methods with same name  in the same class and its subclass with different arguments and optionally different return type. Which overloaded version of the method to be called is based on the reference type of the argument passed at compile time. As the constructor name should be as class name, Overloading can be apply by writing more than one constructor with different type of parameters and their different order.

Some rules we must know about overloading in Java

  •  Overloaded methods must change the argument list.
  •  Overloaded methods can change the return type.
  •  Overloaded methods can declare new or broader checked exacpetions
  •  Overloaded methods can change the access modifier.
  •  Constructors can be overloaded.
 
Also keep in mind below points about overloaded methods:

  1.    appear in the same class or a subclass
 2.    have the same name but,
 3.    have different parameter lists, and,
 4.    can have different return types   
 
 
Example for Constructor overloading:

public class Person {
    String name;
    int age;
    public Person() {
        // do somthing
    }
    public Person(String name, int age) {
        // do somthing
    }
    public Person(int age, String name) {
        // do somthing
    }
    public Person(int age) {
        // do somthing
    }
    public Person(String name) {
        // do somthing
    }
}
In the above example class Person has five different type of constructor with different parameters and their order.
Example for Method overloading:   
public class Person {
    String name;
    int age;
    public void doStuff() {
        // do something
    }
    public void doStuff(String name) {
        // do something
    }
    public void doStuff(int age) {
        // do something
    }
    public void doStuff(String name, int age) {
        // do something
    }
    public void doStuff(int age, String name) {
        // do something
    }
}

In the above example of method overloading the doStuff() method of Person class is overloaded many time with different parameter and parameter order.

0 comments:

Post a Comment