Table of Contents
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:
- The name of the constructor must match the name of the class that it is in.
- Constructors posses no return types; not even the
void
modifier. - 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:
public void Circle() { }
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:
new ClassName(arguments);
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 classsuper()
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:
public Cube(int size, String color, int face) { this.size = size; this.color = color; this.face = face; }
Do this:
public Cube(int size, String color) { this(size, color, 1); } public Cube(int size) { this(size, "black"); } public Cube() { this(5); }
Not this:
public Cube(int size, String color) { this.size = size; this.color = color; this.face = 1; } public Cube(int size) { this.size = size; this.color = "black"; this.face = 1; } public Cube() { this.size = 5; this.color = "black"; this.face = 1; }[Source]
Extra Notes
◄◄◄BACK | NEXT►►►