Constructors: Initializing Your Objects
When you create an object using the new keyword, a special method called a Constructor is called. Its job is to set up the initial state of the object (like setting default values for variables) so the object is ready to use immediately.
1. Rules for Creating Constructors
Constructors look like methods, but they have two very specific rules:
- Same Name: The constructor name must be exactly the same as the Class name.
- No Return Type: Constructors do not have a return type (not even
void).
2. Types of Constructors
A. The Default Constructor
If you don't write any constructor, Java automatically creates a "hidden" one for you that does nothing. This is why you can call new Car() even if you haven't defined a constructor yet.
B. No-Argument Constructor
You can write your own constructor that takes no inputs to set default values.
public class Robot {
String name;
// No-arg constructor
public Robot() {
name = "Guest-Bot";
}
}
C. Parameterized Constructor
This is the most common type. It allows you to pass data into the object the moment you create it.
public class User {
String username;
int id;
// Parameterized constructor
public User(String name, int userId) {
username = name;
id = userId;
}
}
3. Using the this Keyword
Inside a constructor, you will often see the keyword this. It is used to distinguish between the class field and the parameter if they have the same name.
public class Book {
String title;
public Book(String title) {
this.title = title; // "this.title" is the field, "title" is the parameter
}
}
💻 Full Practical Example: The Smartphone Factory
Copy this into your editor to see how constructors make object creation faster:
class Phone {
String brand;
int storage;
// Constructor makes it easy to set values instantly
Phone(String brand, int storage) {
this.brand = brand;
this.storage = storage;
}
void displayInfo() {
System.out.println(brand + " with " + storage + "GB storage.");
}
}
public class Main {
public static void main(String[] args) {
// Instead of 4 lines of code, we do it in 1!
Phone p1 = new Phone("Apple", 128);
Phone p2 = new Phone("Samsung", 256);
p1.displayInfo();
p2.displayInfo();
}
}
4. Constructor Overloading
Just like methods, you can have multiple constructors in the same class, as long as they have different parameters.
public class Account {
String owner;
double balance;
// Option 1: Create account with $0
Account(String owner) {
this.owner = owner;
this.balance = 0.0;
}
// Option 2: Create account with initial deposit
Account(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
}
💡 Challenge: The Student Enrollment
Create a class called Student.
- Add fields:
String name,double gpa, andint year. - Create a parameterized constructor that sets all three.
- Create a no-argument constructor that sets the name to "Unknown" and the year to 1.
- In
main, create one student using each constructor and print their details.