What is constructor ?
In Java, a constructor is a special method used to initialize objects. Unlike regular methods, constructors are invoked when an instance of a class is created. They have the same name as the class and do not have a return type. Constructors are essential for setting initial values for object attributes and preparing the object for use.
Why Do We Need Constructors in Java ?
Constructors play a very important role, it ensures that an object is properly initialized before use.
What happens when we don't use constructors:
Without constructors:
- Objects might have undefined or default values.
- Extra initialization methods would be required.
- Risk of improper object state
When Java Constructor is Called?
Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class.
Types of Constructors in Java
- Default Constructor (No-Argument Constructor)
- Parameterized Constructor
- Copy Constructor
1. Default Constructor in Java(No-Argument Constructor)
A constructor that has no parameters is known as default constructor. A default constructor is invisible. And if we write a constructor with no arguments, the compiler does not create a default constructor. Once you define a constructor (with or without parameters), the compiler no longer provides the default constructor. Defining a parameterized constructor does not automatically create a no-argument constructor, we must explicitly define if needed.
For example:
import java.io.*;
// Driver class
class Geeks{
// Default Constructor
Geeks() {
System.out.println("Default constructor");
}
// Driver function
public static void main(String[] args)
{
Geeks hello = new Geeks();
}
}
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor.
import java.io.*;
class Geeks {
// data members of the class
String name;
int id;
Geeks(String name, int id) {
this.name = name;
this.id = id;
}
}
class GFG
{
public static void main(String[] args)
{
// This would invoke the parameterized constructor
Geeks geek1 = new Geeks("Sweta", 68);
System.out.println("GeekName: " + geek1.name
+ " and GeekId: " + geek1.id);
}
}
Copy constructor (TBD)
Reference:https://www.geeksforgeeks.org/java/constructors-in-java/
https://www.datacamp.com/doc/java/constructors
Top comments (0)