jeudi 20 avril 2017

Omit the use of the constructor in children in Java

I try to write a simple example of the decorator pattern.

I have a Printable interface, a concrete classes for printing and abstract class for decorator:

// 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();
  }
}

Note that I use a constructor in abstract PrinterDecorator. So, then I wrote two concrete decorators for printing header and footer of the base content to be printed. Here they are:

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

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

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

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

Here I want the PrinterDecorator children not to redeclare the parent constructor. But I get the next error if I run with comments above:

error: constructor FooterPrinterDecorator in class FooterPrinterDecorator 
cannot be applied to given types;

Also I tried to write default constructor in parent decorator manually. In that case the compiler gives me the same error, but in other context (it expect constructor without arguments even if I give the Printable as a parameter. The call to the constructor:

Printable one = new HeaderPrinterDecorator(new FooterPrinterDecorator(new DisplayPrinter()));
Printable two = new HeaderPrinterDecorator(new HeaderPrinterDecorator(new FooterPrinterDecorator(new PaperPrinter())));

So, can I omit the duplication of the parent constructor in its children?

Aucun commentaire:

Enregistrer un commentaire