deep Java function overloading
Consider a few questions first:
There is an overloaded function for this:
public static void chongZai1(ArrayList list){ System.out.println("ArrayList ");}public static void chongZai1(AbstractList list){ System.out.println("AbstractList ");}public static void chongZai1(List list){ System.out.println("List ");}
1.
public static void main(String[] args) { List list = new ArrayList(); chongZai1(list); ArrayList arrayList = new ArrayList(); chongZai1(arrayList);}
How will it be output?
Output:
List
ArrayList
Concept:
The function or method has the same name, but the argument list is not the same, so the function or method with different parameters of the same name is called the overloaded function or method with each other.
- Overloading a function is a compile-time concept.
- The compile time determines which method should be called based on the type of the parameter variable.
The simple understanding is that
List list = new ArrayList(); chongZai1(list);
Go directly to the function that has the parameter list type
ArrayList arrayList = new ArrayList(); chongZai1(arrayList);
The first way to find a method with the parameter type ArrayList is to find the function that the parameter is the parent of the ArrayList class, and finally the function to find the interface that the parameter is implemented as ArrayList.
If this is the overloaded function:
public static void chongZai1(AbstractList list){ System.out.println("AbstractList ");}public static void chongZai1(AbstractCollection list){ System.out.println("AbstractList ");}public static void chongZai1(List list){ System.out.println("List ");}public static void chongZai1(Serializable list){ System.out.println("List ");} public static void main(String[] args) { ArrayList arrayList = new ArrayList(); chongZai1(arrayList);} 这样编译期就会抛错! 因为它不知道该去掉哪个方法 这些都是父的父类或者实现的接口 集体规则 参考:[https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5)
Deep Java function overloading