netoops blog

Saturday, 24 August 2013

Compare between constructor overloading vs method overloading.



Answer: Overloading in java

Overloading is defining more than one set of statement with same name but different signature. Overloading happens in the within same java class. The overloading can be applied on methods and constructor of the class.

Constructor overloading

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.
For example:
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.

Method overloading

Defining more than one method with the same name but different signature within same class is called method overloading in java. The method signature includes name, parameters and parameters orders. In method overloading the name should be same so to achieve the Method overloading we can define the methods with different parameters and different parameters order.
For Example:
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.

Tech Knowledege
SOCIALIZE IT →
FOLLOW US →
SHARE IT →

0 comments :

Post a Comment

 
Subscribe For Free Updates!

We'll not spam mate! We promise.

Become Our Fan on Social Sites!