zxzx28
zxzx28

Reputation: 15

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 :

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? The program prints as follows : B B B

Upvotes: 1

Views: 75

Answers (2)

Ravi Sharma
Ravi Sharma

Reputation: 170

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.

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. Same as it is called using A's reference as shown below.

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

Upvotes: 2

Greedo
Greedo

Reputation: 3549

It is because the method func in D does not override the same of C as the signature change.

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

Upvotes: 0

Related Questions