parent / child method overriding

132 views Asked by At

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?

3

There are 3 answers

0
JB Nizet On

Call a private internalBar() method from A.foo(), instead of calling the overridable bar(). The A.bar() method can also call internalBar() by default (to avoid code duplication), and still be overridden in subclasses.

0
Morteza Adi On

You should use composition instead of inheritance. for example

public class Test {
    public static void main(String[] args) {
        B b = new B(new A());
        b.foo();
    }
}

class A implements Parent {
    public void foo() {
        System.out.println("A foo");
        bar();
    }

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


interface Parent {
    void foo();
    void bar();
}

class B implements Parent {

Parent wrapped;

public B(Parent p) {
    this.wrapped = p;
}

@Override
public void foo() {
    wrapped.foo();
    System.out.println("B foo");
}

@Override
public void bar() {
    System.out.println("B bar");
}

}
0
Abhay On

If execution of bar() in class B is not a problem you can use super.bar() inside it.