Monday, November 29, 2010

Method overloading is done when we create several methods with the same name. However, Java requires us to include different numbers of parameters.

Below is the revised program where the methods are of default type but to access them, I have to make an instance of the class for me to access each method.

[+/-] show/hide

/*Sample program on methods

public class MethodOverloadingSample2 {

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

BufferedReader br= new BufferedReader(new InputStreamReader(;
MethodOverloadingSample2 myObject=new MethodOverloadingSample2();

System.out.println("Input first number:");
String num1=br.readLine();

System.out.println("Input second number:");
String num2=br.readLine();

System.out.println("Input third number:");
String num3=br.readLine();

System.out.println("Input fourth number:");
String num4=br.readLine();

int a = Integer.parseInt(num1);
int b = Integer.parseInt(num2);
int c = Integer.parseInt(num3);
int d = Integer.parseInt(num4);

System.out.println("Sum of two numbers "+myObject.compute(a,b));
System.out.println("Sum of three numbers: "+myObject.compute(a,b,c));
System.out.println("Sum of three numbers: "+myObject.compute(a,b,c,d));

double compute(int w,int x)
{ return w+x;}

double compute(int w,int x, int y)
{ return w+x+y;}

double compute(int w,int x,int y, int z )
{ return w+x+y+z;}


No comments: