Constructors in Java
A constructor is a block, called when an object is created. When the constructor is called memory of an object is allocated. The basic meaning of the constructor is one who builds something. In object, oriented programming constructor is responsible for the object creation.
Why need of constructors
In object-oriented programming memory is very important, each object allocated some memory if we give memory to all objects and use some of them then rest object memory has gone useless to overcome this we need mechanism it is called a constructor. In the constructor, the size of memory is defined. Whenever we create an object the constructor is called if there is no constructor then the default constructor is called.
Example
HashMap<String,Object> hashmap=new HashMap<String,Object>();
In the process of making the HashMap class object, the constructor of the HashMap class is called and the default memory size is allocated.
public class HashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable {
// Default load factor
final float DFL= 0.75f;
final float load_factor
// default constructor
public HashMap() {
this.load_Factor = DFL;
}
}
Here as we create the HashMap the default load factor is assigned for the object. The constructor is also used to assign the values to the variables.
Rules to write the constructor
There is no return type defined for the constructor, a void return type is also not used.
The name of the constructor needs to be identical to the class name.
It can’t be final, synchronized, abstract and static.
Note If there is a constructor with a return type is called a method.
public class constructorEx {
constructorEx() {
System.out.print("constructor");
}
void constructorEx() {
System.out.print("method");
}
}
Types of Constructors
There are two types of constructors defined in java.
- Default constructor (no-arg constructor)
- Parameterized constructor (With parameters)
Default constructor
A constructor with no parameters called default constructors. If we don’t write any constructor then the compiler will generate a default constructor. The main goal of default constructor is to store a default value to the object like null,0, false, etc;
Example
public class DefaultConsEx{
// Default constructor
DefaultConsEx(){
System.out.printf("Constructor executed.");
}
public static void main(String… s) {
DefaultConsEx m=new DefaultConsEx();
}
}
Output:
Constructor executed.
Parameterized Constructor
As the name suggests constructor with parameters called the parameterized constructor. If you want to initialize your individual value to the class variables then apply the parameterized constructor.
Example
public class ParameterizedConstructorEx {
String q;
Int f;
//constructor with arguments
ParameterizedConstructorEx(String string_q,int int_f){
this.q=string_q;
this.f=int_f;
}
public void printingValue(){
System.out.printf("The string value of s is: "+q);
System.out.println();
System.out.printf("The integer value of x is: "+f);
}
}
public class Main{
public static void main(String... args) {
ParameterizedConstructorEx a=new ParameterizedConstructorEx("Hello",123);
a.printingValue();
}
}
Output:
The string value of s is: Hello
The integer value of x is: 123
➡ Do we have destructors in Java..?
No, As java has a default Garbage collector all object reference is deleted when the object is no longer used.
➡ Can we make constructor private if yes then what is used..?
Yes, we can add a private Access modifier to make the constructor private. If we make it private then it is only used within the class. Like in a singleton design pattern we use a private constructor.
➡ Can we use the final keyword with a constructor..?
No, It gives the compile-time error.on the above example if we make a constructor final.
“ParameterizedConstructorEx.java:5: error: modifier final not allowed here
final ParameterizedConstructorEx(String string_s,int int_x){”
➡ What is returned when the constructor is called..?
You can’t use any return type in the constructor but explicitly it returns the instance of the current class.
Constructor overloading in JAVA
We can also overload the constructor. It behaves like method overloading.
Example
- public class ConstructorOverLoadingEx {
- String con_ty_value = "";
- // constructor overloading
- ConstructorOverLoadingEx(String q, int f) {
- this.con_ty_value = "2 param constructor.";
- }
- ConstructorOverLoadingEx(String q) {
- this.con_ty_value = "1 param constructor.";
- }
- ConstructorOverLoadingEx() {
- this.con_ty_value = "No param constructor.";
- }
- public String typeConstructor() {
- return con_ty_value;
- }
- }
- public class Main {
- public static void main(String... args) {
- ConstructorOverLoadingEx pc = new ConstructorOverLoadingEx("Hello", 123);
- System.out.print(pc.typeConstructor());
- }
- }
Output
2 param constructor.