2

Let's say I have a base class called Vehicle, and another class called Car that extends it. Finally I have a class Luxury that extends Car.

I know I can use the keyword super to invoke a base-class method. How do I invoke a method of the Vehicle class from Luxury?

phs
  • 10,687
  • 4
  • 58
  • 84
McLan
  • 2,552
  • 9
  • 51
  • 85

1 Answers1

2

There is no builtin mechanism for this. You have to create a helper method in the first subclass.

public class A {
    public void myMethod() { ... }
}

public class B extends A {
    public void myMethod() {
        // something
    }

    protected void myMethodA() {
        super.myMethod();
    }
}

public class C extends B {
    public void myMethod() {
        myMethodA();
    }
}
Brett Kail
  • 33,593
  • 2
  • 85
  • 90
  • Thank you, It works .. and If may I, in term of following best practice, when do you advice me to create helper methods ? – McLan May 06 '15 at 10:57
  • 1
    I would do it only as needed, and even then sparingly. This kind of pattern breaks Liskov substitution principle since you should expect that a subclass of a class will behave the same as the class itself. Needing this capability usually means something is misarchitected, but it can be a useful workaround until you have time to refactor. – Brett Kail May 06 '15 at 14:39