Consider the two below concrete classes:
public class A {
protected void foo() {
System.out.println("A foo");
bar();
}
protected void bar() {
System.out.println("A bar");
}
}
public class B extends A {
@Override
protected void foo() {
super.foo();
System.out.println("B foo");
}
@Override
protected void bar() {
System.out.println("B bar");
}
}
public class Test {
public static void main(String[] args) {
B b = new B();
b.foo();
}
}
The output will be:
A foo
B bar
B foo
Which is correct. But what if we need the result to be:
A foo
A bar
B foo
We have to override both methods.
Is there any solution for this in Java Object model?
Call a private
internalBar()
method fromA.foo()
, instead of calling the overridablebar()
. TheA.bar()
method can also callinternalBar()
by default (to avoid code duplication), and still be overridden in subclasses.