Michael Michael - 2 years ago 78
Java Question

How to call abstract method from abstract class called by inherit class

I want to call a method of an abstract class from abstract class called by inherit class.

Abstract class:

public abstract class Abstract {
protected void updateMotionY(float deltaTime) {
System.out.println("Abstrcat updateMotionY");
}
public void update(float deltaTime) {
this.updateMotionY(deltaTime);
}
}


Inherit class:

public class Obj extends Abstract{
@Override
protected void updateMotionY(float deltaTime) {
System.out.println("updateMotionY");
super.updateMotionY(deltaTime);
}
@Override
public void update(float deltaTime) {
super.update(deltaTime);
}
}


Main method class:

public static void main(String[] args) {
(new Obj()).update(10.0f);
}


Whenever I try to call new Obj().update() method in main class, it prints:
updateMotionY and
Abstrcat updateMotionY. I want to get only
Abstrcat updateMotionY.
Can anyone tell me how to resolve this problem?

Answer Source

(new Obj()).update(10.0f) calls Obj::update which calls Abstract::update which calls this.updateMotionY. Because this is an instance of Obj, this calls Obj::updateMotionY.

This prints "updateMotionY".

This then calls super.updateMotionY(deltaTime) which is Abstract::updateMotionY.

This prints "Abstrcat updateMotionY".

That's the end of the call hierarchy and everything unwinds.


Fundamentally your confusion seems to stem from the fact that this.updateMotionY(deltaTime); in the Abstract class resolves to updateMotionY in the Obj class. That's basically the whole point of polymorphism.


One thing you could do is to add a private method (so that it cant be overridden) which contains the actual implementation, and defer to it:

public abstract class Abstract {
    private void motionY(float dt)
    {
        System.out.println("Abstrcat updateMotionY");
    }

    protected void updateMotionY(float deltaTime) {
        motionY(deltaTime);
    }
    public void update(float deltaTime) {
        motionY(deltaTime);
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download