简体   繁体   English

父/子方法覆盖

[英]parent / child method overriding

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? Java Object模型中是否有任何解决方案?

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");
}

}

Call a private internalBar() method from A.foo() , instead of calling the overridable bar() . A.foo()调用私有的internalBar()方法,而不是调用可A.foo()bar() The A.bar() method can also call internalBar() by default (to avoid code duplication), and still be overridden in subclasses. A.bar()方法也可以默认调用internalBar() (以避免代码重复),并且仍然可以在子类中重写。

如果在B类中执行bar()不是问题,可以在其中使用super.bar()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM