Using inherited overloaded methods

后端 未结 11 1718
北荒
北荒 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 06:08

      class ClassA
      {
         public void method( Number n )
         {
            System.out.println( "ClassA: " + n + " " + n.getClass() );
         }// void method( Number n )
    
      }// class ClassA
    
      public class ClassB
         extends
            ClassA
      {
         public void method( Integer d )
         {
            System.out.println( "ClassB: " + d + " " + d.getClass() );
         }// void method( Integer d )
    
         public static void main( String[] args )
         {
            ClassB b = new ClassB(); 
            ClassA a = b; 
            a.method( new Integer( 3 )); // 1. ClassA: 3 class java.lang.Integer
            b.method( new Integer( 4 )); // 2. ClassB: 4 class java.lang.Integer
            b.method( new Float( 5.6 )); // 3. ClassA: 5.6 class java.lang.Float
         }// void main( String[] args )
    
      }// class ClassB
    
    1. Since the two methods are NOT overloaded and the instance is of class a, no dispatch occurs from A to B
    2. B has a best match method, then it's chosen
    3. B can't handle a parameter of type Float, so A method is chosen

提交回复
热议问题