1

I found some similar topics, for instance here, but they did not answer my question in entirely. Question is very simple:

Is it a good practice to call the super() in a subclass' constructor? I know of course, that if I do not make it explicitly, a compiler will do it for me, but I'm asking only in context of the best practices. Do you consider invoking super() in each subclass' constructor as a "triumph of form over substance" ?

I'm working with code which contains uses strategies, so I see, that for many programmers it does not matter at all... For me it does not matter as well now, but maybe I should change it...

Community
  • 1
  • 1
radekEm
  • 4,617
  • 6
  • 32
  • 45
  • 5
    You **have to** do it if the super class doesn't have a default constructor. For example: `class Fruit{ protected String flavor; public Fruit(String flavor) { this.flavor = flavor; } } class Apple extends Fruit { public Apple() { super("sweet"); } }`. Off topic: `super("sweet")` sounds funny :). – Luiggi Mendoza Jun 10 '13 at 09:22
  • I never use the empty `super()` because it's simply redundant, but as @LuiggiMendoza says, `super(...)` can be necessary. – Vincent van der Weele Jun 10 '13 at 09:23
  • Yes, of course. But I meant only the situation in which super can be omitted. – radekEm Jun 10 '13 at 09:31

2 Answers2

3

Good practice? Call what's necessary to correctly initialize your object.

public class Foo {
    private String name;
    public Foo() { this(""); }
    public Foo(String n) { this.name = n; }
}

public class Bar extends Foo {
    private int x;
    public Bar(int y) { this("", y); }
    public Bar(String n, int y) {
        super(n);
        this.x = y;
    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
3

In my opinion explicit super() call is just polluting the code. Default super() call is invented exactly for this purpose - to shorten the code. See SE library source, super() is hardly ever used, eg

public HashMap(int initialCapacity, float loadFactor) {
   if (initialCapacity < 0)
   ...
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275