java constructors in inheritance tutorial

java constructors inheritance tutorial explains us about implicit and explicit constructors in Java. Bodhak Java tutorials explain I detailed about the concept with syntax and implementation of the same is explained with detailed programs.

Since a derived class object contains the elements of a base class object, it is reasonable to want to use the base class constructor as part of the process of constructing a derived class object.


java constructors inheritance tutorial

Constructors are “not inherited”. In a sense, this is a moot point, since they would have a different name in the new class, and can’t be called by name under any circumstances, so, for example, when one calls new Integer(int i) they shouldn’t expect a constructor named Object(int i) to run.

Within a derived class constructor, however, you can use super( parameter list ) to call a base class constructor.

Calling constructor of super class with in subclass:

It must be done as the first line of a constructor.

Therefore, you can’t use both this() and super() in the same constructor function.

If you do not explicitly invoke a form of super-constructor, then super() (the form that takes no parameters) will run.

For the super class, its constructor will either explicitly or implicitly run a constructor for its superclass.

So, when an instance is created, one constructor will run at every level of the inheritance chain, all the way from Object up to the current class.

Implicit calling (super() call):

One base class constructor will always run when instantiating a new derived class object.

If you do not explicitly call a base class constructor, the no-arguments base constructor will be automatically run, without the need to call it as super().

But if you do explicitly call a base class constructor, the no-arguments base constructor will not be automatically run.

The no-arguments (or no-args for short) constructor is often called the default constructor since it is the one that will run by default.