java - 省略了在 Java 子类中使用构造函数

标签 java oop design-patterns

我试着写一个装饰器模式的简单例子。

我有一个Printable接口(interface),一个用于打印的具体类和一个用于装饰器的抽象类:

// for all objects that can be printed
interface Printable {
  public void print();
}


// classes for decorating
class DisplayPrinter implements Printable {
  public void print() {
    System.out.println("Print to the display");
  }
}

class PaperPrinter implements Printable {
  public void print() {
    System.out.println("Print to the paper");
  }
}


// printer decorator for all possible decorators
abstract class PrinterDecorator implements Printable {
  private Printable printer;

  public PrinterDecorator(Printable p) {
    printer = p;
  }

  public void print() {
    if (printer != null)
      printer.print();
  }
}

请注意,我在抽象 PrinterDecorator 中使用了构造函数。 所以,然后我写了两个具体的装饰器来打印要打印的基本内容的页眉和页脚。这里的页脚装饰器是:

class FooterPrinterDecorator extends PrinterDecorator {
  /*public FooterPrinterDecorator(Printable p) {
    super(p);
  }*/

  public void print() {
    super.print();
    System.out.println("Footer");
  }
}

在这里,我希望 PrinterDecorator 子级不要重新声明父级构造函数。但是如果我运行上面的评论,我会得到下一个错误:

error: constructor FooterPrinterDecorator in class FooterPrinterDecorator cannot be applied to given types;
Printable one = new FooterPrinterDecorator(new DisplayPrinter());
                ^
required: no arguments
found: DisplayPrinter
reason: actual and formal argument lists differ in length

我还尝试在父装饰器中手动编写默认构造函数。在那种情况下,编译器会给我同样的错误,但在其他上下文中(它期望构造函数没有参数,即使我将 Printable 作为参数。对构造函数的调用:

Printable one = new FooterPrinterDecorator(new DisplayPrinter());

那么,我可以省略父构造函数在其子构造函数中的重复吗?

最佳答案

你不能;如果您的父类没有默认构造函数,则每个子类都必须实现一个调用父类的构造函数。那是为了保持封装,并且因为构造函数不像方法那样被继承。

不过,您可以做的是在 PrinterDecorator 中使用方法而不是构造函数:

abstract class PrinterDecorator implements Printable {
  private Printable printer;

  public void setDecorator(Printable p) {
    printer = p;
  }

  public void print() {
    if (printer != null)
      printer.print();
  }
}

现在您的 child 不需要弄乱该方法,他们将按原样继承。

关于java - 省略了在 Java 子类中使用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43528352/

相关文章:

java - 使用巴比伦算法计算平方根

c# - 无法在静态方法中使用实例变量

集合和迭代器的 C# 性能

PHP PDO MySQL count() 预处理语句

c++ - 选择正确的子类以编程方式实例化

design-patterns - Windows服务和设计模式

java - 在 Maven 生命周期内安装第 3 方 JAR 与系统范围依赖项

java - Angular js : How to pass "." character into a parameter for $resource

java - 验证多层应用程序输入数据的最佳实践

java - 如何使用 Jackson 和 JsonPointer 查找具有动态节点名称的值