CONSTRUCTOR
What is a constructor ?
A constructor is a block of codes similar
to the method. It is called when an instance
(object) of the class is created.
➢Java constructor constructs an object and it
provides a values for the objects that is why
named as constructor.
Default Constructor
➢A constructor without parameters.
➢Provided automatically by Java if no other constructor
is defined.
EXAMPLE:
class Student {
Student() {
System.out.println ("Default Constructor Called");
}
public static void main(String[] args) {
Student s1 = new Student(); // Calls default
constructor
}}
Parameterized Constructor
➢A constructor that takes arguments (parameters).
➢Used to initialize objects with custom values.
class Student {
String name;
int age;
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("Ram", 20); // Calls parameterized constructor
s1.display();
}
}
Copy Constructor
➢Used to copy values from one object to another.
➢Java does not provide this by default; you must define it manually.
class Student {
String name;
int age;
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); // Calls copy
constructor
s1.display();
s2.display();
}
}