Constructors and Constructors with Arguments in Java
1. Constructors in Java
A constructor is a special method in a class that is automatically called when an object is
created. It has the same name as the class and does not have a return type.
Default Constructor Example
class Car {
String brand;
int year;
Car() {
brand = "Toyota";
year = 2025;
[Link]("Default Constructor Called");
}
}
public class Main {
public static void main(String[] args) {
Car c1 = new Car();
[Link]([Link] + " - " + [Link]);
}
}
2. Parameterized Constructor Example
class Car {
String brand;
int year;
Car(String b, int y) {
brand = b;
year = y;
[Link]("Parameterized Constructor Called");
}
}
public class Main {
public static void main(String[] args) {
Car c1 = new Car("Honda", 2022);
Car c2 = new Car("Hyundai", 2024);
[Link]([Link] + " - " + [Link]);
[Link]([Link] + " - " + [Link]);
}
}