In Java, a constructor is a special method used to initialize objects. Unlike regular methods, constructors are invoked when an instance of a class is created. They have the same name as the class and do not have a return type. Constructors are essential for setting initial values for object attributes and preparing the object for use.
Types of Constructors:
1. Default Constructor:
A default constructor is automatically provided by the Java compiler if no constructors are explicitly defined in the class. It initializes the object with default values.
public class Car {
String model;
int year;
// Default Constructor
public Car() {
model = "Unknown";
year = 0;
}
public static void main(String[] args) {
Car car = new Car();
System.out.println("Model: " + car.model + ", Year: " + car.year);
}
}
2. No-Argument Constructor:
A no-argument constructor is explicitly defined by the programmer and does not take any parameters. It is similar to the default constructor but can include custom initialization code.
class Company {
String name;
// public constructor
public Company() {
name = "Programiz";
}
}
class Main {
public static void main(String[] args) {
// object is created in another class
Company obj = new Company();
System.out.println("Company name = " + obj.name);
}
}
output:
Company name = Programiz
3. Parameterized Constructor:
A parameterized constructor accepts arguments to initialize an object with specific values. This allows for more flexible and controlled initialization of object attributes.
public class Car {
String model;
int year;
// Parameterized Constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}
public static void main(String[] args) {
Car car = new Car("Toyota", 2021);
System.out.println("Model: " + car.model + ", Year: " + car.year);
}
}
Reference :
https://www.datacamp.com/doc/java/constructors
https://www.programiz.com/java-programming/constructors
Top comments (0)