contractors

Java Constructors

Java Constructors

A constructor in Java is a special method used to initialize objects. It has the same name as the class and is called when an object is created. Constructors can be either default (no arguments) or parameterized (with arguments).

Default Constructor

public class Car {
    String make;
    String model;

    // Default Constructor
    public Car() {
        make = "Unknown";
        model = "Unknown";
    }

    public void displayInfo() {
        System.out.println("Make: " + make + ", Model: " + model);
    }

    public static void main(String[] args) {
        Car car1 = new Car();  // Calling default constructor
        car1.displayInfo();
    }
}
    

This example shows a Car class with a default constructor. When the object is created, it automatically assigns default values to the make and model attributes.

Parameterized Constructor

public class Car {
    String make;
    String model;

    // Parameterized Constructor
    public Car(String make, String model) {
        this.make = make;
        this.model = model;
    }

    public void displayInfo() {
        System.out.println("Make: " + make + ", Model: " + model);
    }

    public static void main(String[] args) {
        Car car2 = new Car("Toyota", "Corolla");  // Calling parameterized constructor
        car2.displayInfo();
    }
}
    

This example uses a parameterized constructor to pass values to the make and model attributes when creating an object.