2. Method Overloading
In Java it is possible to define two or more methods
within the same class that share the same name, as
long as their parameter declarations are different.
The methods are called overloaded methods.
The process is called method overloading.
When an overloaded method is invoked, Java uses
the type and/or number of arguments t0 determine
which version of the overloaded method to actually
call.
3. Example
public Class OverLoadDemo
{
void test( )
{
System.out.println(“No parameters”);
}
void test(int a)
{
System.out.println(“a: ”+a);
}
void test( int a, int b)
{
System.out.println(“a: ”+ a+ “b: ”+ b);
}
double test(double a)
{
System.out.println(“a: ”+ a);
return a*a;
}
}
4. Example cont..
public class OverLoadDemoDriver
{
public static void main(String args[])
{
OverLoadDemo o=new OverLoadDemo( );
o.test( );
o.test(10);
o.test(10,20);
double d;
d=o.test( 10.7);
}
}
Note: 1. Method overloading doesn’t depend on the return type.
2. Automatic type casting is allowed while calling methods.
6. Constructor Overloading
Just like methods constructors can be overloaded.
One class can have more than one constructors
defined.
All the rules of constructor overloading are the same
as that of method overloading.
7. Example
public class Student
{
//data members or instance variables
private int rollNo;
public int semester;
//behavior or methods are kept public
// Overloaded Constructors
public Student( )
{
rollNo=10;
semester=2;
}
public Student(int r)
{
rollNo=r;
semester=2;
}
public Student(int r, int s)
{
rollNo=r;
semester=s;
}
public void displayValues( )
{
System.out.println(rollNo);
System.out.println(semester);
}
}
8. Example cont..
public class StudentDriver
{
public static void main(String args[ ])
{
Student s, s1,s2;
s=new Student( );
s1=new Student(23);
s2=new Student(45,3);
s.displayValues();
s1.displayValues();
s2.displayValues();
}
}