简体   繁体   English

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

[英]How does inheritance work in this bit of code?

So guys I've been playing around with inheritance and I've stumbled upon this program:伙计们,我一直在玩 inheritance,我偶然发现了这个程序:

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);
    }
}

So how come even though A and C are implemented exactly the same way in the final few lines, A's methods get overriden by B, but C's don't get overriden by D?那么为什么即使 A 和 C 在最后几行中以完全相同的方式实现,A 的方法被 B 覆盖,但 C 的方法没有被 D 覆盖? The program prints as follows: BBB程序打印如下: BBB

Because Class D function definition is more general than C. C's function takes B type parameter but D function takes type A parameter which is a parent of B. It is more general than a function defined in C.因为 Class D function 定义比 C 更通用。C 的 function 采用 B 类型参数,但 D function 采用类型 A 参数,它是 B 的父级。它比 88340040658981837 中定义的 88340040658981837 更通用

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

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

Variable c is pointing to D's object so c.func(b) invokes method defined in D. A is a parent of B hence B's method is called.变量 c 指向 D 的 object,因此 c.func(b) 调用 D 中定义的方法。A 是 B 的父级,因此调用 B 的方法。 Same as it is called using A's reference as shown below.与使用 A 的引用调用相同,如下所示。

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

It is because the method func in D does not override the same of C as the signature change.这是因为D中的方法func没有覆盖与签名更改相同的C

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

This will result in an override of the method这将导致重写该方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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