Constructors

Programmers can't imagine OOP without constructor and destructor functions. Constructor is a special function that helps you instantiate an object of a class. Whenever you instantiate an object, a default constructor method is called.
Let's say we want to create a Rectangle
object with a specific width and height (5x6
). You would probably do it like below:
1// Main.java
2public class Main {
3 public static void main(String[] args) {
4 Rectangle rect = new Rectangle();
5 rect.setHeight(5);
6 rect.setHeight(6);
7 }
8}
Now, let's see what is actually happening behind the scenes.
1Create all the attributes in memory with default values (0 for `height` and `width`).
2Create a class reference in memory that has all the attributes.
3Call 2 setter functions to reassign the attributes.
We can see that the attributes are first set to the default (0) when creating the instances. They are then overwritten with setter methods. Imagine you have a class with 10 attributes and you need to set all the attributes to create a usable object. In that case, you would need to call 10 setters which will increase the size of the code and make the code harder to read. This is where a constructor can help. Constructor is a function that is called during instantiation to initialize the attributes of the new object along with any other things you need to do.
Here is the same code to create a 5x6 rectangle but with only 1 line of constructor call.
1// Main.java
2public class Main {
3 public static void main(String[] args) {
4 Rectangle rect = new Rectangle(5,6);
5 }
6}
Of course, we also need to define this constructor method which takes 2 values when creating from the class:
1// Rectangle.java
2public class Rectangle extends Shape {
3 protected int height;
4 protected int width;
5
6 // Default Constructor
7 public Rectangle() { }
8
9 // User specified constructor
10 public Rectangle(int height, int width) {
11 this.height = height;
12 this.width = width;
13 }
14
15 // Rest of the methods and Attributes
16}
Constructors are very special because they have syntax which differs from typical methods in some languages. Constructors do not return a value (not even null
). You may notice that they don't even have a return type (not even void
).
Constructors are really powerful for several reasons. Suppose each object needs to dynamically create an array of variable size in it as an attribute. The best way to allocate the memory for that array in the heap would be through constructors. Or if you want to instantiate other objects inside that class, you need to do that inside the constructor.
1// A random class
2public class MyClass {
3 protected MyAnotherClass myProperty;
4 protected int[] myArray;
5
6 public MyClass(int propValue, int arraySize) {
7 myProperty = new MyAnotherClass(propValue);
8 myArray = new int[arraySize];
9 }
10}
There are various constructors depending on their use cases. Let's look at some of them in more detail.