继承在这段代码中是如何工作的?

How does inheritance work in this bit of code?

伙计们,我一直在研究继承,我偶然发现了这个程序:

public class HelloWorld {
    static class A {
        void f() { System.out.println("A"); }
    }

    static class B extends A {
        void f() { System.out.println("B"); }
    }

    static class C {
        void func(B b) { b.f(); }
    }

    static class D extends C {
        void func(A a){ a.f(); }
    }

    public static void main(String args[]) {
        ( (new D())).func( (A) (new B()));
        A a =  new B();
        a.f();
        B b = new B();
        C c = new D();
        c.func(b);
    }
}

那么为什么即使在最后几行中 A 和 C 的实现方式完全相同,A 的方法 被 B 覆盖,但 C 没有被 D 覆盖? 程序打印如下: 乙 乙 B

这是因为D中的方法func没有覆盖C的相同方法作为签名更改。

static class C {
    void func(B b) { b.f(); }
}
static class D extends C {
    void func(B a){ a.f(); }
}

这将导致覆盖方法

因为ClassD函数定义比C更通用。C的函数接受B类型参数,但D函数接受类型A参数,它是B的父类。它比C中定义的函数更通用.

static class D extends C {
    void func(A a){ 
        a.f(); 
    }
}

  B b = new B();
  C c = new D();
  c.func(b);

变量 c 指向 D 的对象,因此 c.func(b) 调用 D 中定义的方法。A 是 B 的父级,因此调用 B 的方法。与使用 A 的引用调用相同,如下所示。

  A a =  new B();
  a.f();