Java 中通过重写一个方法来扩展抽象类的最佳实践

我有一个接口I1、一个A1实现的抽象类I1和许多扩展的类C1...。nA1


现在,一个类正在为 的MethodC3实现一种特殊行为,其中每个其他扩展类正在实现一种默认行为。methodAI1A1


public interface I1 {

  public void methodA();

}

public abstract class A1 implements I1 {

  public void methodA(){

    //default behaviour

  }

  //other methods

}

public class C1 extends A1 {

  //do nothing regarding methodA, because the default behaviour is desired

  //other methods

}

public class C2 extends A1 {

  //do nothing regarding methodA, because the default behaviour is desired

  //other methods

}

public class C3 extends A1 {

  public void methodA(){

    //special behaviour

  }

  //other methods

}

现在,对我来说,这似乎不是最好的解决方案,因为很难找出它C3是覆盖其父级的某些方法。这有最佳实践吗?


一只名叫tom的猫
浏览 67回答 1
1回答

慕虎7371278

我会将所有常见方法移至A1另一个抽象级别(我们称之为ABase),并声明A1它们A2的特殊行为(如果有)。这样,如果C3添加更多相同类型的类,则不需要再次重新定义methodA。public interface I1 {  public void methodA();}public abstract class ABase implements I1 {  //other methods}public abstract class A1 extends ABase {  public void methodA(){    //default behaviour  }}public abstract class A2 extends ABase {  public void methodA(){    //default behaviour  }}public class C1 extends A1 {  //do nothing regarding methodA, because the default behaviour in A1 is desired  //other methods}public class C2 extends A1 {  //do nothing regarding methodA, because the default behaviour in A1 is desired  //other methods}public class C3 extends A2 {  //do nothing regarding methodA, because the default behaviour in A2 is desired  //other methods}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java