Constructors In Java
Everything You Need to Know In 2023
Everything You Need to Know In 2023
A Constructor is a block of code that is invoked every time when an object is created using the new keyword. Constructor declarations look like method declarations except that they use the name of the class and have no return type.
Its primary task is to initialize the object values.
It can have a set of instructions/statements that gets executed at the time of object creation.
class ConstructorDemo{
//Constructor for ConstructorDemo class
public ConstructorDemo(int id, String name, double marks) {
this.id = stidartGear;
this.name =name;
this.marks = marks;
}
}
The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. If the class has no explicit superclass, then it calls the no-argument constructor as every class extends the Object class.
Constructor(s) of a class should have the same name as that of the class.
Constructor declaration can have access modifiers to control its accessibility.
Constructors cannot be abstract, final, static and synchronized.
A Constructor can have single initialization and can be used from multiple constructors of the same class(Constructor Chaining[discussed later in the blog] ).
Supports Constructor overloading[discussed later in the blog].
Default Constructor - If we don’t define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class. The Java compiler provides a default constructor if we don't define any constructor in our class.
Non-Parameterized (No-Argument) Constructor - Functionally same as default but in this case, we will define it explicitly.
Parameterized Constructor -A constructor that has parameters is known as parameterized constructor. If we want to initialize the fields of the class with our own values, then use a parameterized constructor.
public class ConstructorChainingDemo {
private int id;
private String name;
private String result;
// Example of a no-arg constructor
public ConstructorChainingDemo() {
System.out.println("Inside No-Arg Constructor");
}
// Example of a paramertized constructor
public ConstructorChainingDemo(int id , String name, ) {
System.out.println("Inside Parameterized Constructor");
}
}
OTHER JAVA TOPICS
XYZ
ABC
Superclass constructor is automatically called by your compiler if your constructor is default or non- parameterized.
package coderoversduo;
public class SuperKeywordDemo {
private int id;
private String name;
public SuperKeywordDemo() {
System.out.println("No argument constructor");
}
public SuperKeywordDemo(int id, String name) {
System.out.println("Parameterized Constructor");
}
}
class Test extends SuperKeywordDemo {
private String address;
public Test(int id, String name, String address) {
//super(id, name);
/* writing super is not mandatory because no-arg constructor is present. Compiler will implicitly call super*/
this.address = address;
}
}
But it is mandatory to specify super when you are dealing with parameterized constructors of the superclass. The super() has to be called in the first line of the constructor as the parent class constructor should be invoked before the child class constructor.
package coderoversduo;
public class SuperKeywordDemo {
private int id;
private String name;
//Removed the no-argument constructor
public SuperKeywordDemo(int id, String name) {
System.out.println("Parameterized Constructor");
}
}
class Test extends SuperKeywordDemo {
private String address;
public Test(int id, String name, String address) {
super(id, name); //declaring super is mandatory now.
this.address = address;
}
}
It is a technique wherein we will have multiple Constructors with the same name but different parameters.
In scenarios wherein we need to initialize an object of a class in multiple ways, we opt for constructor overloading.
Let us take an example of an existing Java class StringBuffer.
It has three constructors.
StringBuffer() -> Creates an empty string buffer with an initial capacity of 16.
StringBuffer(String str) -> Creates a string buffer with the specified string.
StringBuffer(int capacity) -> Creates an empty string buffer with the specified capacity as length.
String Buffer will respond based on what parameters you are sending in the constructor while object creation.
Similarly, you can check for constructors of classes like String, Thread etc for better understanding.
package coderoversduo;
class ConstructorOverloadingCode {
private int id;
private String name;
private String result;
// Constructor With Single Parameter
public ConstructorOverloadingCode(int id) {
this.id = id;
System.out.println("Inside Constructor With single Parameter :: " +id);
}
// Constructor With Double Parameter
public ConstructorOverloadingCode(int id, String name) {
this.id = id;
this.name = name;
System.out.println("Inside Constructor With double Parameter :: " +id+ "," + name);
}
// Constructor With Triple Parameter
public ConstructorOverloadingCode(int id, String name, String result) {
this.id = id;
this.name = name;
this.result = result;
System.out.println("Inside Constructor With triple Parameter :: " + id + "," + name + "'" + result);
}
}
public class ConstructorOverloadingDemo {
public static void main(String[] args) {
//Calling the same constructor with different Patameters
ConstructorOverloadingCode objectFirst = new ConstructorOverloadingCode(1);
ConstructorOverloadingCode objectSecond = new ConstructorOverloadingCode(2, "Coderover");
ConstructorOverloadingCode objectThird = new ConstructorOverloadingCode(3, "Coderover","Pass");
}
}
Constructor Chaining refers to the technique of calling one constructor from another constructor provided both the constructor are of the same class.
1) It lets maintain your initializations from a single location while providing multiple constructors to the user.
2)Reduces boilerplate code.
this() should always be the first statement in the constructor else you will get an error message. Failing to do so will cause the below exception:
Exception in thread “main” java.lang.Error : Unresolved compilation problem: Constructor call must be the first statement in a constructor
This example demonstrates how constructor chaining can be implemented.
package coderoversduo;
public class ConstructorChainingDemo {
private int id;
private String name;
private String result;
// Constructor With Single Parameter
public ConstructorChainingDemo(int id) {
// Calls constructor with Double Parameter
this(id, "John");
System.out.println("Calling constructor with Double Parameter");
}
// Constructor With Double Parameter
public ConstructorChainingDemo(int id, String name) {
// Calls constructor with Triple Parameter
this(id, name, "Pass");
System.out.println("Calls constructor with Triple Parameter");
}
// Constructor With Triple Parameter
public ConstructorChainingDemo(int id, String name, String result) {
this.id = id;
this.name = name;
this.result = result;
System.out.println("Single Initialization, Multiple Calls From Different Constructors");
}
}
Constructor initializeS an object whereas method exhibits the functionality of an object.
The Constructor does not return any value where the method may or may not return a value.
Constructors are invoked implicitly whereas methods are invoked explicitly.
The Constructor has the same name as that of the class name whereas a method can have any name except for that of the class.