Constructors in Java

Heeah
Dec 30, 2023

--

It’s used to initialize objects. The constructor is called when an abject of a class is created using a new() keyword, It can be used to set initial values for object attributes.

public class Car {
// Field or attribute of the class
private String brand;

// Constructor with a parameter
public Car(String brand) {
this.brand = brand;
}

// Getter method for accessing the field
public String getBrand() {
return brand;
}

// Main method
public static void main(String[] args) {
// Creating an instance of Car using the constructor
Car myCar = new Car("Toyota");

// Accessing the field using the getter method
System.out.println("Brand: " + myCar.getBrand());
}
}

--

--