-
Has the same name as the class.
-
No return type (not even void).
-
Called automatically at object creation.
-
Can be parameterized or non-parameterized.
Types of Constructors:
|
Type |
Description |
|
Default
Constructor |
No
parameters. Java provides it by default if none is defined. |
|
Parameterized
Constructor |
Takes
arguments to initialize fields. |
|
Copy
Constructor (Manual) |
Used to copy
data from one object to another (not built-in like C++). |
public class Student {
Student() {
System.out.println("Default constructor called");
}
public static void main(String[] args) {
Student s1 = new Student(); // Constructor is called
}
}
public class Student {
String name;
int age;
// Constructor with parameters
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("Mansi",24); // Constructor is called
s1.display();
}
}
class Student {
String name;
int age;
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
// Copy constructor
Student(Student s) {
name = s.name;
age = s.age;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student("Ravi", 22);
Student s2 = new Student(s1); // Copy constructor called
s1.display();
s2.display();
}
}
Name: Ravi, Age: 22
Name: Ravi, Age: 22
package com.studyopedia;
import java.util.Scanner;
class Student {
String name;
int rollNo;
// ✅ 1. Default Constructor
Student() {
name = "Not Assigned";
rollNo = 0;
System.out.println("Default constructor called");
}
// ✅ 2. Parameterized Constructor
Student(String n, int r) {
name = n;
rollNo = r;
System.out.println("Parameterized constructor called");
}
// ✅ 3. Copy Constructor
Student(Student s) {
name = s.name;
rollNo = s.rollNo;
System.out.println("Copy constructor called");
}
// Method to display data
void display() {
System.out.println("Name: " + name + ", Roll No: " + rollNo);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// ➤ Using default constructor
Student s1 = new Student();
s1.display();
// ➤ Taking user input for parameterized constructor
System.out.print("\nEnter student name: ");
String name = sc.nextLine();
System.out.print("Enter roll number: ");
int roll = sc.nextInt();
// ➤ Using parameterized constructor
Student s2 = new Student(name, roll);
s2.display();
// ➤ Using copy constructor
Student s3 = new Student(s2);
s3.display();
sc.close();
}
}
Output:
Default constructor called
Name: Not Assigned, Roll No: 0
Enter student name: Prasanjeet
Enter roll number: 81901
Parameterized constructor called
Name: Prasanjeet, Roll No: 81901
Copy constructor called
Name: Prasanjeet, Roll No: 81901