MOD2 Part2
MOD2 Part2
Method Overloading
Method Overloading
Having more than one method with a same name is called as method overloading. To
implement this concept, the constraints are:
One can have more than one constructor for a single class if the number and/or type of arguments are different. Consider the following
code:
class OverloadConstruct
{
int a, b;
OverloadConstruct()
{
System.out.println("Constructor without arguments");
}
OverloadConstruct(int x)
{
a=x;
System.out.println("Constructor with one argument:"+a);
}
OverloadConstruct(int x, int y)
{
a=x; b=y;
System.out.println("Constructor with two arguments:"+ a +"\
t"+ b);
}
}
class OverloadConstructDemo
{
public static void main(String args[])
{
OverloadConstruct ob1= new
OverloadConstruct();
OverloadConstruct ob2= new
OverloadConstruct(10);
OverloadConstruct ob3= new
OverloadConstruct(5,12);
Using Objects as Parameters
Just similar to primitive types, even object of a class can also be passed as a parameter to any method. Consider the example given below –
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
class FactDemo
{
public static void main(String args[])
{
Factorial f= new Factorial();
void setc(int i)
{
c = i;
}
int getc()
{
return c;
}
}
class AccessTest
{
public static void main(String args[])
{
Test ob = new Test();
ob.a = 10;
ob.b = 20;
// ob.c = 100; // inclusion of this line is
Error!
ob.setc(100);
System.out.println("a, b, and c: " + ob.a + " " +
ob.b + " “ +ob.getc());
}
}
Understanding static