forked from tugul/CoreJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMethodOverload.java
More file actions
53 lines (49 loc) · 2.23 KB
/
Copy pathMethodOverload.java
File metadata and controls
53 lines (49 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package methods;
/**
* - Method overload
* When there are same named methods with different signature
*
* - Method signature
* Parameter list and their order
* But return type, access modifier, optional specifier or exception list are irrelevant
*
* - In case of autoboxing
* Java calls most specifically matched one from overloaded methods
* If can't find, it looks for next one(only ONE level upper)
* Generally, it follows below one of below step to match parameter:
* : Exact match by parameter type
* : Match with superclass type
* : Convert to larger primitive type
* : Convert to autoboxed type/Wrapper class
* : Varargs
*/
public class MethodOverload {
// Below are valid overloading of methods, except for last one
public void run(int miles){}
public void run(short miles){}
public void run(long miles){}
public boolean run(){ return true; }
private void run(int mile, byte feet){ }
private void run(byte feet, int mile){ }
public void run(byte feet, int mile) throws Exception { } // DOES NOT COMPILE, exception list is irrelevant
// Varargs
void jump(int[] meter) {}
void jump(int ... meter) {} // DOES NOT COMPILE, both accepts single int array
// AutoBoxing
static void fly(int miles) { System.out.println("10"); }
static void fly(Integer miles) { System.out.println("30"); }
static void fly(Long miles) { System.out.println("100"); }
static void fly(Number miles) { System.out.println("600"); }
static void fly(Object miles) { System.out.println("900"); }
public static void main(String[] args) {
fly(2); // 10 (int miles)
fly((byte)2); // 10 (int miles) byte --> int (larger primitive type)
fly(new Integer(1)); // 30 (Integer miles)
fly(2L); // 100 (Long miles) long --> Long
fly(2f); // 600 (Number miles) float --> Float (extends Number)
fly(2.); // 600 (Number miles) double --> Double (extends Number)
fly("2"); // 900 (Object miles) String --> Object
fly(true); // 900 (Object miles) boolean --> Boolean (extends Object)
fly(new int[]{}); // 900 (Object miles) Array --> Object
}
}