In Java, there are two main types of constructors:
Default Constructor (No-Argument Constructor)
- A constructor that does not accept any parameters is called a default constructor.
- If no constructor is defined in a class, Java provides a default constructor that initializes the object with default values. However, if you provide your own constructor, Java will not provide this default constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Car { String model; int year; // Default constructor public Car() { model = "Unknown"; year = 2024; } void display() { System.out.println("Model: " + model); System.out.println("Year: " + year); } } public class Main { public static void main(String[] args) { // Creating an object using the default constructor Car car = new Car(); car.display(); } } //Output Model: Unknown Year: 2024 |
Parameterized Constructor
- A constructor that accepts one or more parameters is called a parameterized constructor.
- This allows you to initialize an object with specific values at the time of creation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Car { String model; int year; // Parameterized constructor public Car(String model, int year) { this.model = model; this.year = year; } void display() { System.out.println("Model: " + model); System.out.println("Year: " + year); } } public class Main { public static void main(String[] args) { // Creating an object using the parameterized constructor Car car = new Car("Tesla", 2025); car.display(); } } //Output Model: Tesla Year: 2025 |