9

Is it mandatory to call base class constructor in Java? In C++ it was optional, so I am asking this.

When I extend ArrayAdapter, I get this error: "Implicit super constructor ArrayAdapter<String>() is undefined. Must explicitly invoke another constructor"

So, what is the purpose of calling base constructor? When I create object base class constructor will call & then it comes to derived right.

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
Naruto
  • 9,476
  • 37
  • 118
  • 201
  • You may not have a rrayAdapter() constructor. If you add a default constructor in the base class, it should be fine. – Chetter Hummin Apr 22 '12 at 04:48
  • Related : [Java error: Implicit super constructor is undefined for default constructor](http://stackoverflow.com/questions/1197634/java-error-implicit-super-constructor-is-undefined-for-default-constructor). – Lion Apr 22 '12 at 04:52
  • So, is it some thing like DerivedClass(int x, int y): BaseClass(y), in c++???. right?? Also one more doubt, in the above mechanism, base class constructor class twice or once? – Naruto Apr 22 '12 at 08:24

2 Answers2

11

The no-args constructor is called implicitly if you don't call one yourself, which is invalid if that constructor doesn't exist. The reason it is required to call a super constructor is that the superclass usually has some state it expects to be in after being constructed, which may include private variables that can't be set in a sub-class. If you don't call the constructor, it would leave the object in a probably invalid state, which can cause all kinds of problems.

ricochet1k
  • 1,232
  • 9
  • 11
  • So, is it some thing like DerivedClass(int x, int y): BaseClass(y), in c++???. right?? Also one more doubt, in the above mechanism, base class constructor class twice or once? – Naruto Apr 22 '12 at 08:23
  • Yes, that's right. Java only allows you to call one constructor in a constructor, either a base class or forwarding to another constructor in the current class, so the base class constructor can only be called once. – ricochet1k Apr 23 '12 at 16:56
0

It's not necessary to call the no-args constructor of super class. If you want to call a constructor with args, user super keyword like show below:

super(arg1, ...);
James Gan
  • 6,988
  • 4
  • 28
  • 36