Java中的多态方法
public class Main { public void test(Object o) { System.out.println("Object"); } public void test(String s) { System.out.println("String"); } public static void main(String[] args) { Main that = new Main(); that.test(null); } }
这段代码运行的结果是
J:\test>java Main
String
J:\test>
因为Java处理null时会优先处理更确切的对象
如果此时还有一个多态方法是ArrayList,程序会报错(编译阶段),因为不知道去适配String还是ArrayList
J:\test>javac Main.java Main.java:14: error: reference to test is ambiguous that.test(null); ^ both method test(String) in Main and method test(ArrayList) in Main match 1 error
如果是基础数据类型和对象类型,则会适配对象类型
J:\test>type Main.java import java.util.ArrayList; public class Main { public void test(Object o) { System.out.println("Object"); } public void test(String s) { System.out.println("String"); } // public void test(ArrayList a){ // System.out.println("ArrayList"); // } public void test(int i){ System.out.println("int"); } public static void main(String[] args) { Main that = new Main(); that.test(null); } } J:\test>javac Main.java J:\test>java Main String J:\test>
如果只有基础数据类型和Object,因为Object是对象,则调用Object
J:\test>type Main.java import java.util.ArrayList; public class Main { public void test(Object o) { System.out.println("Object"); } // public void test(String s) { // System.out.println("String"); // } // public void test(ArrayList a){ // System.out.println("ArrayList"); // } public void test(int i){ System.out.println("int"); } public static void main(String[] args) { Main that = new Main(); that.test(null); } } J:\test>javac Main.java J:\test>java Main Object J:\test>
如果只有基础数据类型,则编译报错,因为java不支持int与null转换
J:\test>javac Main.java Main.java:17: error: incompatible types: <null> cannot be converted to int that.test(null); ^ Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error J:\test>