Careeroza
Constructors
What is a Constructor?
A constructor is a special method that runs when you create an object with new. It has the same name as the class and no return type. Its job is to put the new object into a valid starting state.
- Default constructor: if you write no constructor, Java adds an empty no-argument one for you.
- Parameterized constructor: takes values, e.g.
new Student("Asha", 21). - As soon as you write any constructor, Java no longer adds the default one.
- Constructors can be overloaded (several constructors with different parameter lists).
Default and Parameterized Constructors
Example
Two constructors in one class. Java picks the one that matches the arguments.
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Asha", 21);
s1.show();
s2.show();
}
}
class Student {
String name;
int age;
Student() { // no-argument constructor
name = "Unknown";
age = 18;
}
Student(String n, int a) { // parameterized constructor
name = n;
age = a;
}
void show() {
System.out.println(name + " is " + age + " years old");
}
}Output
Unknown is 18 years old Asha is 21 years old
Constructor Chaining with this()
One constructor can call another constructor of the same class with this(...). This avoids repeating the same setup code. The this(...) call must be the first statement.
Example
public class Main {
public static void main(String[] args) {
System.out.println(new Pizza());
System.out.println(new Pizza("Large"));
System.out.println(new Pizza("Medium", "Paneer"));
}
}
class Pizza {
String size;
String topping;
Pizza() {
this("Regular"); // calls Pizza(String)
}
Pizza(String size) {
this(size, "Cheese"); // calls Pizza(String, String)
}
Pizza(String size, String topping) {
this.size = size;
this.topping = topping;
}
public String toString() {
return size + " pizza with " + topping;
}
}Output
Regular pizza with Cheese Large pizza with Cheese Medium pizza with Paneer
Practice
Exercise: Create a class BankAccount with fields holder and balance. Add a constructor that takes only the holder (balance starts at 0) and one that takes both. Use this(...) so the logic is written once.
Show answer
class BankAccount {
String holder;
double balance;
BankAccount(String holder) {
this(holder, 0);
}
BankAccount(String holder, double balance) {
this.holder = holder;
this.balance = balance;
}
}