Loading

A constructor is a method used to initialize the object. It is automatically called when a class is instantiated.


 Types of Constructor


1. Default Constructor:

  • Constructors declared without parameters are called Default constructors
  • It provides default values (i.e.- 0, NULL) to objects.

Syntax:

Class_name ( ) 
{  
    // body
}


 Example:

package quipohouse;
class Message {
	Message() {
		System.out.println("QUIPO HOUSE");
	}

	public static void main(String[] args) {
		Message obj = new Message();
	}
}


Output:

QUIPO HOUSE

2 . Parameterized Constructor:

  • Constructors declared with parameters are called Parameterized constructors.
  • It provides different values to objects.

Syntax:

Class_name(para1,para2 )
{  
     // body
}


Example:

package quipohouse;
public class Identifier {
	String msg, msg1;
	Identifier(String msg, String msg1) {
		// This keyword refer current class object
		this.msg = msg;
		this.msg1 = msg1;
	}

	void message() {
		System.out.println(msg + "" + msg1);
	}

	public static void main(String[] args) {
		Identifier obj = new Identifier(" Message ", " msg ");
		obj.message();
	}
}


Output:

Message  msg 

3 . Copy Constructor: 

  • Java does not provide a default copy constructor, but we can create one manually.
  • It copies data from one object to another.
Example:
class Employee { String name; int age; // Parameterized Constructor Employee(String name, int age) { this.name = name; this.age = age; } // Copy Constructor Employee(Employee e) { this.name = e.name; this.age = e.age; } void display() { System.out.println("Name: " + name + ", Age: " + age); } public static void main(String[] args) { Employee e1 = new Employee("John", 25); Employee e2 = new Employee(e1); // Copy Constructor e1.display(); e2.display(); } }

Output:
Name: John, Age: 25 Name: John, Age: 25

4 . Copy Constructor: 

  • One constructor can call another constructor using this().
  • Helps in code reusability.
Example:
class Student { String name; int age; // Default Constructor calling Parameterized Constructor Student() { this("Unknown", 0); } Student(String name, int age) { this.name = name; this.age = age; } void display() { System.out.println("Name: " + name + ", Age: " + age); } public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student("Alice", 22); s1.display(); s2.display(); } }

Output:
Name: Unknown, Age: 0 Name: Alice, Age: 22

Constructor vs Method


FeatureConstructorMethod
NameSame as Class NameAny Name
Return TypeNo Return TypeCan have Return Type
CallAutomatically called on object creationMust be called explicitly
OverloadingYesYes
OverridingNoYes


Key Point
  • A constructor must have the same name as the class name.
  • Constructors do not have any return type.
  • A constructor cannot be can't be final, static, abstract, or synchronized.