-4

I know that super is called when you create a subclass in Java. But is super called in every constructor, or only in the first constructor of the subclass?

Thanks

albad17
  • 1
  • 1
  • 4
    Please give a concrete example of your question, ideally with some indication of what you've tried in order to answer it for yourself. – Jon Skeet Feb 23 '15 at 17:00
  • Note that you don't need to call super in all cases. Give some examples of what you mean. – m0skit0 Feb 23 '15 at 17:00
  • What do you mean by the first constructor? – kraskevich Feb 23 '15 at 17:00
  • *Every* constructor calls *a* parent constructor - explicitly (via `super(..)`) or implicitly though an assumed call-the-default-parent-constructor, possibly though another constructor (via `this(..)`) of the same type. – user2864740 Feb 23 '15 at 17:13

2 Answers2

1

But is super called in every constructor, or only in the first constructor of the subclass?

Firstly there is nothing like first Constructor or Second Constructor , Since Constructor calling will be based on Object Creation.

if you create Object this way

 new MyClass(); //then no-argument constructor will be called

and if Object Created in this way

new MyClass("ABC");// then parameterized constructor will be called

So super() is called in each and every Constructor in the first line .

Note : if you explicitly call other constructor in the same class using this() then in that scenario super() will not be called in existing constructor

Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

You can call another constructor from the same class like this:

MyClass(int someValue) { this(someValue, false); .... }

In this case the super constructor is not called, but it will be called in the first constructor which doesn't call another constructor from the class.

Andrei Vajna II
  • 4,642
  • 5
  • 35
  • 38