Constructor:
Constructor is a special method used to initialize objects. It is called automatically When a object of a class is created.
Characteristics:
- Constructor name must be same as class name
- It has no return type not even void
- It is automatically invoked when the object is created.
- Can be overloaded i.e multiple constructors in one class with different parameters.
Types of constructors:
Two Types of Constructors
1.Default Constructor
A Constructor with no parameters.
Provided automatically by the constructor if no constructor is written.
Program For Defult:
class Vehicle {
Vehicle() {
System.out.println("Car is created");
}
public static void main(String[] args) {
Vehicle v = new Vehicle(); // Constructor is called
}
}
output:
car is created.
Parameterised Constructor:
Constructor that accepts arguments to initialize the object with custom values.
Program for Parametersized:
class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println(name + " " + age);
}
public static void main(String[] args) {
Student s1 = new Student("Ram", 20);
s1.display();
}
}
Output:
Ram 20
Top comments (0)