Polymorphism and method overloading

前端 未结 5 757
深忆病人
深忆病人 2020-12-25 11:52

I have a quick and straighforward question:

I have this simple class:

public class A
{
    public void m(Object o)
    {
      System.out.println(\"m         


        
5条回答
  •  执念已碎
    2020-12-25 12:38

    Object is the default type in Java. If you refactor your m(Object o) method to m(String o) you'll have a compile time error saying that the call m(null) is ambiguous because Java cannot determine which class between String and Number defaults to null

    Other than that, between m(Object o) and m(Number o), calling m(null) will call m(Number o) because it's the most specialized method. You would need to cast null into an Object (or anything not an instance of Number) otherwise.

    a.m((String) null);
    

提交回复
热议问题