Constructors
Constructors are special methods used to initialize objects when they are created. They are called automatically when you use the new keyword. Constructors ensure that objects start with valid initial values, making your code more robust and easier to use. In this lesson, you'll learn about different types of constructors and how to use them effectively.
What is a Constructor?
A constructor is a special method that has the same name as the class and no return type (not even void). It is automatically called when an object is created using the new keyword.
Constructor Characteristics
- Has the same name as the class
- No return type (not even
void) - Automatically called when object is created
- Cannot be called explicitly like regular methods
- Used to initialize instance variables
Default Constructor
If you don't define any constructor in your class, Java automatically provides a default constructor (a constructor with no parameters) that does nothing except initialize instance variables to their default values.
public class Student {
String name;
int age;
// No constructor defined - Java provides default constructor
// Default constructor: public Student() { }
}
// Using the default constructor
Student student = new Student(); // Default constructor called automatically
However, if you define any constructor (even a parameterized one), Java will not provide the default constructor. You must explicitly define it if you need it.
Click Run to execute your code
Parameterized Constructor
A parameterized constructor accepts parameters to initialize instance variables with specific values. This is much more convenient than setting values after object creation.
public class Student {
String name;
int age;
// Parameterized constructor
public Student(String studentName, int studentAge) {
name = studentName;
age = studentAge;
}
}
// Create object with initial values
Student student = new Student("Alice", 20);
Benefits of Parameterized Constructors
- Initialize objects with values in one step
- Ensure required fields are set
- Make code more readable and concise
- Prevent objects from being created in invalid states
Constructor Overloading
Like methods, constructors can be overloaded. This means you can have multiple constructors with different parameter lists. The compiler determines which constructor to call based on the arguments you provide.
public class Rectangle {
double width;
double height;
// Default constructor
public Rectangle() {
width = 1.0;
height = 1.0;
}
// Constructor with one parameter (square)
public Rectangle(double side) {
width = side;
height = side;
}
// Constructor with two parameters
public Rectangle(double w, double h) {
width = w;
height = h;
}
}
// Different ways to create Rectangle objects
Rectangle rect1 = new Rectangle(); // Uses default constructor
Rectangle rect2 = new Rectangle(5.0); // Creates a square
Rectangle rect3 = new Rectangle(4.0, 6.0); // Creates a rectangle
The 'this' Keyword
The this keyword refers to the current object. It's commonly used in constructors and methods to distinguish between instance variables and parameters with the same name.
Click Run to execute your code
Key uses of this:
- Refer to instance variables:
this.namerefers to the instance variable - Call other constructors:
this()calls another constructor (must be first line) - Return the current object: Useful for method chaining
- Pass current object: Pass
thisas a parameter to methods
Constructor Chaining
You can call one constructor from another using this(). This is called constructor chaining and must be the first statement in the constructor.
public class Student {
String name;
int age;
String email;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student(String name, int age, String email) {
this(name, age); // Call the other constructor
this.email = email;
}
}
Constructor Execution Flow
Understanding how constructors are executed is important. Below is a visual representation:
Common Mistakes
1. Adding return type to constructor
// Wrong - this is a method, not a constructor
public void Student(String name) {
this.name = name;
}
// Correct - no return type
public Student(String name) {
this.name = name;
}
2. Assuming default constructor always exists
public class Student {
String name;
public Student(String name) {
this.name = name;
}
}
// Wrong - default constructor not available
Student student = new Student(); // Error! No default constructor
// Correct - use parameterized constructor
Student student = new Student("Alice");
3. Not using 'this' when parameter names match instance variables
public class Student {
String name;
// Wrong - assigns parameter to itself, instance variable unchanged
public Student(String name) {
name = name; // Does nothing!
}
// Correct - use 'this' to refer to instance variable
public Student(String name) {
this.name = name;
}
}
4. Calling constructor not as first statement
public class Student {
String name;
int age;
// Wrong - this() must be first statement
public Student(String name, int age) {
this.name = name; // Error! Can't have code before this()
this(age);
}
// Correct - this() is first statement
public Student(String name, int age) {
this(age);
this.name = name;
}
}
Exercise: Create a Bank Account Class
Task: Create a BankAccount class with:
- A default constructor that initializes balance to 0
- A parameterized constructor that sets initial balance
- Instance variables: accountNumber (String) and balance (double)
- Use the
thiskeyword appropriately
Click Run to execute your code
Show Solution
public class BankAccount {
String accountNumber;
double balance;
// Default constructor
public BankAccount() {
this.accountNumber = "";
this.balance = 0.0;
}
// Parameterized constructor
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
void displayInfo() {
System.out.println("Account: " + accountNumber);
System.out.println("Balance: $" + balance);
}
}
public class Exercise {
public static void main(String[] args) {
BankAccount account1 = new BankAccount();
account1.accountNumber = "ACC001";
account1.displayInfo();
BankAccount account2 = new BankAccount("ACC002", 1000.0);
account2.displayInfo();
}
}
Summary
- Constructors initialize objects when they are created
- Constructor name must match the class name and have no return type
- Java provides a default constructor only if you don't define any constructor
- Parameterized constructors allow initialization with specific values
- Constructors can be overloaded (multiple constructors with different parameters)
- The
thiskeyword refers to the current object - Use
thisto distinguish instance variables from parameters this()can call another constructor (must be first statement)
What's Next?
Now that you understand constructors, the next lesson covers Methods in Classes, which shows you how to define and use methods that operate on your objects' data.
Enjoying these tutorials?