A constructor is a special method used to initialize objects.
It runs automatically when an object is created.
class Car {
Car() {
System.out.println("Car created");
}
}
What is super()?
Super() is a call to the parent class constructor. It must be the first statement in a child constructor.
class Vehicle {
Vehicle() {
System.out.println("Vehicle constructor");
}
}
class Car extends Vehicle {
Car() {
super(); // calls Vehicle()
System.out.println("Car constructor");
}
}
Car car = new Car(); // Vehicle Constructor β Car Constructor
Key Points
- Every constructor implicitly calls super() if no other constructor call is specified.
- You can use super(args) to call specific parent constructor.
- If parent has no default (no-arg) constructor, you must explicitly call a matching one.
- super() is only used inside a constructor - not in methods.
Constructor Overloading + super()
class Vehicle {
Vehicle(String name) {
System.out.println("Vehicle: " + name);
}
}
class Bike extends Vehicle {
Bike() {
super("Bike"); // Calls parent constructor with arg
System.out.println("Bike ready");
}
}
Comparison
super()
vs this()
Keyword | Calls⦠| Used For |
---|---|---|
this() | Another constructor (same class) | Constructor chaining within class |
super() | Parent class constructor | Inheritance-base constructor chaining |
Tip
Be ready to explain:
- why super() must come first,
- what happens if the parent doesnβt have a default constructor,
- how super() helps with constructor chaining.
Parent: _OOP