20 October 2010

0 What is Method Overloading in Java?

Method Overloading in Java

Two or more methods in a Java class can have the same name, if their argument lists are different, this feature is known as Method Overloading.
Argument list could differ in
  • No of parameters
  • Data type of parameters
  • Sequence of parameters
void print(int i){
    System.out.println(i);
}
void print(double d){
    System.out.println(d);
}
void print(char c){
    System.out.println(c);
}

Method Overloading in Java is Static Polymorphism
Calls to overloaded methods will be resolved during compile time, In otherwords, when the overloaded methods are invoked, JVM will choose the appropriate method based on the arguments used for invocation. For example, if the print method is invoked with an int argument, the overloaded print method that accepts an int parameter will be chosen by the JVM.

Example of Different implementation of Method Overloading in Java
void add (int a, int b)
void add (int a, float b)
void add (float a, int b)
void add (int a, int b, float c)

Methods differing only in return type
Methods differing only in return type will not be treated as overloaded methods, it will be compilation error. For Example, the below given methods will give compilation error.
void print(int i){
    System.out.println(i);
}
int print(int i)){
    System.out.println(i);
    return i;
}

Overloading the Constructors
Just like other methods, constructors also can be overloaded.

public class Student{
    public Student(){
        mark = 100;
    }
    public Student(int rollNo, double mark){
        this.rollNo = rollNo;
        this.mark = mark;
    }
}


0 comments:

Feeds Comments

Please give your valuable comments.