Monday, November 29, 2010

Java's Method Overloading

 Typically, Java's method must be defined with unique names. However, it is also possible that methods may have similar names provided that the number of parameters is  unique from each method otherwise you will be having trouble in compiling our program.

See the program for such sample. The use of static on methods allow us to use directly the methods in our calling method.

[+/-] show/hide

/*Sample program on methods

public class MethodOverloadSample1 {

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

BufferedReader br= new BufferedReader(new InputStreamReader(;

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 "+compute(a,b));
System.out.println("Sum of three numbers: "+compute(a,b));
System.out.println("Sum of three numbers: "+compute(a,b,c,d));

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

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

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


No comments: