Java Constructors
A constructor is a special method used to initialize a new object, sharing the same name as its class and having no return type. It runs automatically when an object is created with new.
If you don't define any constructor, Java provides a default no-argument constructor automatically. You can also overload constructors to allow different ways of creating objects.
class C {
C() { }
C(int x) { }
}Default vs parameterized constructors
A default constructor takes no arguments; a parameterized constructor accepts arguments to set initial field values at creation time.
Constructor overloading
A class can have multiple constructors with different parameter lists, giving flexible ways to create objects.
class Car {
String brand;
Car(String brand) {
this.brand = brand;
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Honda");
System.out.println(myCar.brand);
}
}HondaThe constructor sets the brand field using the argument passed to new Car("Honda").
Key points
- A constructor shares its class's name and has no return type.
- Java provides a default no-arg constructor if none is defined.
- Constructors can be overloaded for flexible object creation.
- this refers to the current object inside a constructor.
