0

Say I have this Super Class:

public class MySuperClass {

protected void MyPrMethod() {
        //Do...
    }

    public void MyPuMethod() {
        MyPrMethod();
    }
}

and this Sub Class:

public class MySubClass extends MeSuperClass {
    public MySubClass() {}

    @Override protected void MyPrMethod() {
        //Do this instead...
    }
}

Then into main:

MySubClass mySubClass = new MySubClass ();
mySubClass.MyPuMethod();

Which MyPrMethod will mySubClass.MyPuMethod() call?

Edit: I got downvoted thrice already. I cannot try it now since I am not at home, though knowing the answer right now will help me designing a part in a program I am making.

Mickael Bergeron Néron
  • 1,472
  • 1
  • 18
  • 31

3 Answers3

3

Because the method MyPrMethod() is overridden in the subclass, the subclass implementation will be called.

The actual method that gets called depends on the object on which it gets called.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
2

The subclass's version of the method will be used. When MyPuMethod calls MyPrMethod, the class (MySubClass) is first checked for the desired method, and only if it's not defined there are the parents recursively searched. The fact that the method we're currently executing is defined in a different class does not change this.

Asterlune
  • 59
  • 3
  • At runtime, no search should occur. The object's class can reference a vtable of the virtual methods it supports. – Andy Thomas Jul 17 '13 at 21:47
1

The MyPrMethod from subclass MySubClass will get called.

rvd
  • 157
  • 1
  • 1
  • 9