Saturday, August 27, 2011

Method OverLoding and Polymorphism concept with example


In java it is possible to create more than one methods with same name but different parameters.
This is known as method overloading.
Now when we call that method by an object then java interpreter find out the method name first and then match the number of parameters.
This process or this technique is known as Polymorphism.

In my below example I used two methods of same name "area()" and one has two parameters and other one has one parameter.
Now from the main method we do call area() method with two parameters when we enter our choice as "1" and call area() method with one parameter when we enter our choice as "2".

//Overloading example(OverLoadingExample.java)
public class OverLoadingExample
{
int l,w;
public void area(int a,int b)
{
l=a;
w=b;
System.out.println("area of rectangle = "+(l*w)+" sq.unit");
}

public void area(int a)
{
l=w=a;
System.out.println("area of square = "+(l*w)+" sq.unit");
}
}

//Main class (MyMainClass.java)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MyMainClass
{
public static void main(String args[]) throws IOException
{

int choice,a,b;
OverLoadingExample OverLoadingExampleObject = new OverLoadingExample();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

try
{
System.out.print("Enter 1 to get the area of rectangle and 2 for square:");
choice = Integer.valueOf(br.readLine()).intValue();

switch (choice)
{
case 1:
{
System.out.println("Enter length:");
a=Integer.valueOf(br.readLine()).intValue();

System.out.println("Enter width:");
b=Integer.valueOf(br.readLine()).intValue();

OverLoadingExampleObject.area(a,b);
break;
}
case 2:
{
System.out.println("Enter length/width:");
a=Integer.valueOf(br.readLine()).intValue();

OverLoadingExampleObject.area(a);
break;
}
default:
System.out.println("Please enter 1 or 2 to calculate area of rectangle and square respectively.");
break;
}
}
catch (NumberFormatException ne)
{
System.out.println(ne.getMessage()+" Please enter a numeric value.");
}
}
}


Output1=>
Enter 1 to get the area of rectangle and 2 for square:1
Enter length:
12
Enter width:
9
area of rectangle = 108 sq.unit


Output2=>
Enter 1 to get the area of rectangle and 2 for square:2
Enter length/width:
9
area of square = 81 sq.unit

No comments:

Post a Comment