In Java, constructors are special methods used to initialize objects of a
class. They have the same name as the class and do not have a return
type. Constructors are called automatically when an object of the class is
created. There are several types of constructors in Java:
Default Constructor: If a class does not have any constructor defined
explicitly, Java provides a default constructor automatically. This default
constructor initializes instance variables to their default values and takes no
arguments.
public class MyClass {
// Default constructor (provided by Java if not explicitly defined)
public MyClass() {
// Initialization code
}
}
Parameterized Constructor: A parameterized constructor is a constructor
that accepts parameters. It allows you to initialize instance variables with
specific values when an object is created.
public class Person {
private String name;
private int age;
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}}
A copy constructor is a special constructor in a class that creates a new
object by copying the values from an existing object of the same class.
Here's a simple program demonstrating the concept of a copy constructor
in Java:
public class Student {
private String name;
private int age;
// Parameterized constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// Copy constructor
public Student(Student other) {
this.name = other.name;
this.age = other.age;
}
// Getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
// Creating a Student object using the parameterized constructor
Student student1 = new Student("Alice", 20);
// Creating another Student object using the copy constructor
Student student2 = new Student(student1);
// Displaying the details of both students
System.out.println("Student 1:");
System.out.println("Name: " + student1.getName());
System.out.println("Age: " + student1.getAge());
System.out.println("\nStudent 2 (copied from Student 1):");
System.out.println("Name: " + student2.getName());
System.out.println("Age: " + student2.getAge());
}
}
We have a Student class with two private instance variables name and
age.
We define a parameterized constructor that takes name and age as
parameters to initialize a Student object.
We also define a copy constructor that takes another Student object as a
parameter and copies its name and age values to initialize a new Student
object.
In the main method, we create a Student object student1 using the
parameterized constructor.
Then, we create another Student object student2 using the copy
constructor, passing student1 as a parameter.
Finally, we print out the details of both students to verify that the copy
constructor correctly copied the values from student1 to student2.
output:
Student 1:
Name: Alice
Age: 20
Student 2 (copied from Student 1):
Name: Alice
Age: 20