Method Overload rules

Method Overload rules

Java allow method to be overloaded, but there is a rules to be followed.

Rules:

  • Match by type exactly, same parameter types
  • Larger primitive type, Eg called parameter int, method parameter long
  • Autoboxed type
  • Varargs array to …[type]
public void run( byte a ) {  } 
public void run( short a) {  }
public void run( char a) {  }
public void run( int a) {  } 
public void run( long a) {  } 
public void run( float a) {  } 
public void run( double a) {  } 
public void run( Byte a) {  } 
public void run( Short a) {  } 
public void run( Character a) {  }
public void run( Integer a) {  } 
public void run( Long a) {  } 
public void run( Float a) {  } 
public void run( Double a) {  }

Example: Match by type exactly

public static void main(String[] args) {
	test(1, 2);
}
	
public static void test(int a, int b) {
	System.out.println("run int test");
}
	
public static void test(long a, long b) {
	System.out.println("run long test");
}

## Output ## 
run int test

Example: Larger primitive type

public static void main(String[] args) {
  short a = 1, b = 2; 
  test(a, b);
}

public static void test(byte a, byte b) {
  System.out.println("run byte test");
}

public static void test(double a, double b) {
  System.out.println("run double test");
}

## Output ##
run double test"

Example: Autoboxed type

public static void main(String[] args) {
	test(1, 2);
}

public static void test(Integer a, Integer b) {
	System.out.println("run Integer test");
}

## Output ##
run Integer test

Example: Varargs array

public static void main(String[] args) {
    test(1, 2);
    test(1, 2, 3);
    test(1, 2, 3, 4);
}

public static void test(int ...args) {
    System.out.println("run varags test");
}
## Output ##
run varags test
run varags test
run varags test

Write a Reply or Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.