☕ Java Beginner

What is a constructor in Java?

Answer

A constructor is a special method that is automatically called when an object is created with new. It has the same name as the class and no return type (not even void). Constructors initialize the object's state: public Car(String color, int speed) { this.color = color; this.speed = speed; }. If you do not define any constructor, Java provides a default no-argument constructor that initializes fields to their default values. Constructors can be overloaded (multiple constructors with different parameters). One constructor can call another using this() (constructor chaining).