Tim
Tim

Reputation: 4365

Java - Confused about a particular inheritance scenario

Say I have a class called A, and in A there's a method called myMethod(). Now say I make a subclass of A, called SubA, and in SubA I override myMethod() to make it do what I want it to. Now say I have another method in A called myOtherMethod() which calls myMethod() (from within the same class). I do not override myOtherMethod() in SubA. If I now call myOtherMethod() from inside SubA, it will clearly run A's myOtherMethod(). But does this now call the myMethod() as defined in A, or as defined (and overridden) in SubA?

To further confuse things, does it matter at all whether myMethod() were an interface method for some interface that class A implemented?

Upvotes: 0

Views: 206

Answers (2)

assylias
assylias

Reputation: 328598

It is easy to try - the fact that A implements an interface or not does not make a difference:

public class A {

    public void myMethod() {
        System.out.println("A.myMethod()");
    }

    public void myOtherMethod() {
        System.out.println("A.myOtherMethod()");
        myMethod();
    }

    public static class SubA extends A {

        @Override
        public void myMethod() {
            System.out.println("SubA.myMethod()");
        }
    }

    public static void main(String[] args) {
        A a = new A();
        SubA subA = new SubA();
        a.myMethod(); //A.myMethod()
        subA.myMethod(); //SubA.myMethod()
        a.myOtherMethod(); //A.myOtherMethod() + A.myMethod()
        subA.myOtherMethod(); //A.myOtherMethod() + SubA.myMethod()
    }

}

Upvotes: 1

viliam
viliam

Reputation: 523

If you create instance of SubA then calling method myOtherMethod() (which is in A) calls method myMethod() defined in SubA because it overrides method defined in A.

Upvotes: 1

Related Questions