Using inherited overloaded methods

后端 未结 11 1768
北荒
北荒 2020-12-15 05:50

I have two classes:

public class ClassA {
    public void method(Number n) {
        System.out.println(\"ClassA: \" + n + \" \" + n.getClass());
    }
}
         


        
11条回答
  •  佛祖请我去吃肉
    2020-12-15 05:58

    You had the following code

    Class A a = new ClassB(); 
    a.method(3);
    

    But imagine you have a method where "a" and "3" are passed to you as a parameter and you still execute the same code

    public void foo(A a, Number n)
    {
        a.method(n);
    }
    

    The compiler does not know whether you are going to pass Class A or Class B (or Number or Integer). It must still resolve the method so it can do type checking for the return value from a.method

提交回复
热议问题