Constructors in Core Java
What is a Constructor in Java?
A constructor is a special method used to initialize objects. It has the same name as the class and
does not have a return type.
Types of Constructors in Java:
1. Default Constructor (No parameters)
2. Parameterized Constructor (With parameters)
1. Default Constructor
Syntax:
class ClassName {
ClassName() {
// code to initialize object
Example:
class Car {
Car() {
System.out.println("Car is created");
public static void main(String[] args) {
Car myCar = new Car(); // Constructor is called here
}
Output:
Car is created
Explanation:
- Car() is the constructor.
- It is automatically called when the object myCar is created.
2. Parameterized Constructor
Syntax:
class ClassName {
ClassName(parameter1, parameter2, ...) {
// use parameters to initialize
Example:
class Student {
String name;
int age;
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
void display() {
System.out.println("Name: " + name + ", Age: " + age);
public static void main(String[] args) {
Student s1 = new Student("Elisha", 21);
s1.display();
Output:
Name: Elisha, Age: 21
Explanation:
- Constructor Student(String n, int a) is used to set values while creating object s1.
Important Points:
- Constructor name must be same as class name.
- No return type, not even void.
- Called automatically when an object is created.
- Constructors can be overloaded.
- Java provides a default constructor if none is defined.