java继承问题 extends

mac2024-01-27  33

If both A and B implement a method f() for example, and the static type is A and the dynamic type involved is C for a method invocation, then B.f() will be invoked:

B extends A, C extends B public A.f() {} public B.f() {} A x = new C(); // static type A, dynamic type C x.f(); // B.f() invoked

Simplifying greatly: first the static types of both receiver (type A) and arguments (no args) are used to decide the best-matching (most specific) method signature for that particular invocation, and this is done at compile-time. Here, this is clearly A.f().

Then, in a second step at runtime, the dynamic type is used to locate the actual implementation of our method signature. We start with type C, but we don’t find an implementation of f(), so we move up to B, and there we have a method B.f() that matches the signature of A.f(). So B.f() is invoked. (调用)

In our example we say that method B.f() overrides method A.f(). The mechanism of overriding methods in a type hierarchy is called subtype polymorphism.


这是期中考试中出的一道题 在下列表格中写正确的结果,(例:“b行” m1() 意思就是 b.m1() ,出现ERROR的话打叉)

class A{ void m1(){System.out.print("A's m1"); } void m2(){System.out.print("B's m1"); } } class B extends A{ void m2(){System.out.print("B's m2");} } class C extends B{ void m2(int x){System.out.print("C's m2");} } public class Main{ public static void main(String[ ] args){ A a =new A(); B b =new B(); C c =new C(); A a1 =new C(); } }

最新回复(0)