Constructor in Java
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created.
public class Car {
String model;
String color;
// Constructor
public Car(String model, String color) {
this.model = model;
this.color = color;
}
void displayDetails() {
System.out.println("Model: " + model + ", Color: " + color);
}
public static void main(String[] args) {
Car myCar = new Car("Tesla Model S", "Red");
myCar.displayDetails();
}
}
Constructor Chaining in Java
Constructor chaining is the process of calling one constructor from another constructor with respect to the current object.
public class Car {
String model;
String color;
int year;
// Constructor 1
public Car(String model, String color) {
this.model = model;
this.color = color;
}
// Constructor 2
public Car(String model, String color, int year) {
this(model, color); // Calling constructor 1
this.year = year;
}
void displayDetails() {
System.out.println("Model: " + model + ", Color: " + color + ", Year: " + year);
}
public static void main(String[] args) {
Car myCar = new Car("Tesla Model S", "Red", 2020);
myCar.displayDetails();
}
}
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have more than one constructor that differ in parameter lists.
public class Car {
String model;
String color;
int year;
// Constructor 1
public Car(String model, String color) {
this.model = model;
this.color = color;
}
// Constructor 2
public Car(String model, String color, int year) {
this.model = model;
this.color = color;
this.year = year;
}
void displayDetails() {
System.out.println("Model: " + model + ", Color: " + color + ", Year: " + year);
}
public static void main(String[] args) {
Car myCar1 = new Car("Tesla Model S", "Red");
Car myCar2 = new Car("Tesla Model 3", "Blue", 2021);
myCar1.displayDetails();
myCar2.displayDetails();
}
}
Initializer Block in Java
Initializer blocks in Java are used to initialize instance variables. They run each time when an object of the class is created.
public class Car {
String model;
String color;
int year;
// Initializer block
{
year = 2020;
}
// Constructor
public Car(String model, String color) {
this.model = model;
this.color = color;
}
void displayDetails() {
System.out.println("Model: " + model + ", Color: " + color + ", Year: " + year);
}
public static void main(String[] args) {
Car myCar = new Car("Tesla Model S", "Red");
myCar.displayDetails();
}
}