8.3 Java | Using Constructors to Construct Objects

Constructor Name, Return Type & Invocation

The new operator is used to invoke a constructor to make an object.

Constructors are special types of methods with 3 unique traits:

  1. The name of the constructor must match the name of the class that it is in.
  2. Constructors posses no return types; not even the void modifier.
  3. Only constructors are invoked with the new operator to make objects- that means constructors are the ones responsible for initializing the objects in the first place.

But constructors also have similarities, for example constructors can be overloaded like regular methods. Overloaded here means that multiple constructors can the same name but different “signature”; in other words, do/contain different things than constructors of the same name. This fact allows you to make many objects of same type, but with different initial data values.

Another thing you should know when working with constructors is that there is no void modifier, as I’ve mentioned before. If you use a void keyword in front of a constructor, you don’t have a constructor but end up with a method. For example, in:

the Circle() is a method, not a constructor.

So far, you know that constructors are used to make objects. To make an object from a class, you must invoke the constructor of the by putting in front of it the new operator. The syntax for this is as follows:

Know that a class’s constructor can come without arguments or statements. Such a constructor can be known as a no argument constructor.

Know that a class can be defined without the use of constructors inside it.

Know that a public constructor with no arguments, ie. empty body, is automatically provided as the default constructor if there are no constructors explicitly defined in a class.

This() & Super()

  • this() calls another constructor in the same class
  • super() calls a constructor in the parent class (superclass)

If you need to call the parent constructor super() (from the superclass – with or without parameters) in a child constructor (in the subclass), you need to do it as the first statement in the constructor, otherwise it won’t work. [Source]

Constructor Organization

As much as possible, overloaded constructors should call the next most complex version of the constructor:

Given:

Do this:

Not this:

[Source]

Extra Notes


◄◄◄BACK | NEXT►►►

What's Your Opinion?