Using inherited overloaded methods

后端 未结 11 1760
北荒
北荒 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:50

    a is of type ClassA so the methods in ClassB will not be visible to instance a unless it is declared as ClassB

    ClassB a = new ClassB(); 
    

    will produce your expected output. Number is the supertype of Integer. So whatever you pass in will be autoboxed to appropriate subtype and the method in ClassA will be called. Try passing

    a.method(3.0f) // Float
    a.method(3.0) // Double
    

提交回复
热议问题