Any way to _not_ call superclass constructor in Java?

后端 未结 13 1358
误落风尘
误落风尘 2020-12-15 04:16

If I have a class:

class A {
   public A() { }
}

and another

class B extends A {
   public B() { }
}

is t

13条回答
  •  [愿得一人]
    2020-12-15 04:24

    The closest you can achieve to the desired behaviour is to delegate initialisation normally performed in the constructor to a template method, which you then override in your subclass implementation. For example:

    public class A {
      protected Writer writer;
    
      public A() {
        init();
      }
    
      protected void init() {
        writer = new FileWriter(new File("foo.txt"));
      }
    }
    
    public class B extends A {
      protected void init() {
        writer = new PaperbackWriter();
      }
    }
    

    However, as other people have noted this can typically indicate a problem with your design and I typically prefer the composition approach in this scenario; for example in the above code you could define the constructor to accept a Writer implementation as a parameter.

提交回复
热议问题