简体   繁体   中英

Java casting, overide and polymorphism

In the following example, I reckon it's something about run time polymorphism, but I can't figure out why y.m1(x) prints out A . My understanding is that y.m1() calls the m1() method in class B , because y contains an object of B . Since x is passed to it as a parameter, and it belongs to the class A which is wider than B , won't it lead to a run-time error? Plus how come z.m1(y) prints out A too?

Many thanks in advance!

 class A {
     public void m1(A a) {
         System.out.println("A");
     }
 }
 class B extends A {
      public void m1(B b) {
        System.out.println("B");
      }
  }
 class D2 {
       public static void main(String[] args) {
           A x = new A();
           A y = new B();
           B z = new B();
        } 
  }

B 's m1 does not override A 's m1 method, as it does not take the same parameter. So B class consist of two overloaded m1 methods, one taking an A object, the other taking a B object. Only static polymorphism can be used here, that's why you can see this behavior.

The dynamic type of an object (the type used in the new) is it's actual runtime type: it defines the actual methods that are present for an object.

The static type of an object reference (a variable) is a compile-time type: it defines, or rather declares, which methods can be called on the object the variable references.

Because the parameter type of both the dynamic type and the static type are different, we dynamic type doesn't override the method, but overloads it.

If the parameter types would have been the same, the output would be B...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM