Why does eclipse automatically add a java super() method in a constructor when I use the editors code generator?

StackOverflow https://stackoverflow.com/questions/23644520

Domanda

When I write a constructor in my java class, I typically do not invoke super() in there. When I generate the constructor from eclipse source code editor, why does it always add the super() in there?

Am I wrong for not adding this by default in the constructors I write? Any thing wrong with leaving the super() call in the constructor if I decide to use eclipse code generator?

È stato utile?

Soluzione 2

As @Kon mentioned in his comment, an empty constructor in Java contains an implicit call to the superclass constructor.

Moreover, a non-empty constructor without an explicit call to super() will have an implicit call at the top.

The only time when it is wrong to leave the super() call there is if you intend to call a different superclass constructor yourself, with parameters.

See this question for more details.

Update: Consider the following code, which illustrates the scenario where it is wrong to leave the super() generated by eclipse.

public class Foo{
    public Foo(int a, int b) {
        System.out.println("Foo constructor with-args is called");
    }
    public Foo() {
        System.out.println("Foo with no-args is called");
    }
}
class Bar extends Foo {
    public Bar() {
        // Implicit call to super()
        super(); 

        // Explicit call to super(a,b);
        // This will not compile unless the call above has been removed.
        super(1,2);
    }
}

Altri suggerimenti

As @Kon correctly points out, there is an implicit call to the default super constructor anyway (this can be easily verified by checking the bytecode with javap -c). If you don't want Eclipse to make it explicit, simply check the "Omit call to default constructor super()" checkbox at the bottom of the constructor creation GUI.

enter image description here


Am I wrong for not adding this by default in the constructors I write?

No, as long as long as you're referring to the default super constructor call super(). If the super constructor takes parameters, for example, then you need to make the call explicit.

Any thing wrong with leaving the super() call in the constructor if I decide to use eclipse code generator?

No, not at all.

Nothing wrong it's just a coding style preference. Some people like to write code that is implicit and some don't.

If you don't call super constructor from your child class constructor compiler will place call to super's default constructor in byte code for you. See this SO question as well

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top