Wink Saville’s Blog

December 13, 2007

Java - Inheritance and constructors

Filed under: java, programming — wink @ 1:43 am

Here is a thread answering the question I had today concerning how a classes super class constructors are called. I had made a class which extended the Android Handler and everything worked. Later I came back and saw that I had a call to the super constructor commented out:

class StateMachine extends Handler {
StateMachine(String name) {
//super.Handler();
mName = name;
/* Other stuff */
}

Today I looked at this and wondered how it was working as I wasn’t calling the super class constructor. First the reason I had commented it out was because the syntax was wrong, it should have been “super();” not “super.Handler();”. But that didn’t answer the question, how/when should super class constructors be called in Java?

Turns out the answer is that the default constructor of the super class is always called if there is no explicit calls to super constructors, that is the reason my StateMachine class worked. In the above the last post we see:

Constructors are not inherited. The constructors that exist in a child class are completely independent of the ones that exist in the parent class.

If you do not define any expclicit constructors, the class will have the default, no-arg, do-nothing c’tor. If you define one or more c’tors, the class will not automatically have the default c’tor anymore.

Constructor rules:

1) Every class has at least one ctor.

1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().

1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a

public MyClass() {}

if you want one.

1.3) Constructors are not inherited.

2) The first statement in the body of any ctor is either a call to a superclass ctor

super(…)

or a call to another ctor of this class

this(…)

2.1) If you do not explicitly put a call to super(…) or this(…) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super’s no-arg ctor

super()

as the first call. The implicitly called ctor is always super’s no-arg ctor, regardless of whether the currently running ctor takes args.

2.2) There is always exactly one call to either super(…) or this(…) in each constructor, and it is always the first call. You can’t put in more than one, and if you put one in, the compiler’s implicitly provided one is removed.

So I was lucky, sometimes that’s better than smart:)

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress