Java Constructors
In Java, a Constructor is a special type of method that is called when a new object of a class is created. Its main purpose is to provide initial values for the object's instance variables.
Characteristics of Constructors
- Name matches class name: The constructor's name must exactly match the name of the class it belongs to.
- No return type: Constructors have no return type, not even
void. This is a key difference from regular methods. - Automatically called: When an instance of a class is created using the
newkeyword, the constructor is automatically called.
Default Constructor
If you don't define any constructor in your class, the Java compiler automatically provides a no-argument default constructor with an empty body. This constructor initializes instance variables to their default values (0 for numbers, false for booleans, null for reference types).
public class Car {
String model;
int year;
// No constructor defined here, so compiler provides a default public Car() {}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Calls the default constructor
System.out.println("Model: " + myCar.model); // Output: null
System.out.println("Year: " + myCar.year); // Output: 0
}
}Important: Once you define any constructor in your class (with or without parameters), the compiler will not provide the default constructor anymore.
Parameterized Constructor
Usually, we want to set meaningful initial values for object attributes when creating them. This can be achieved by defining constructors with parameters.
public class Dog {
String name;
int age;
// This is a parameterized constructor
public Dog(String dogName, int dogAge) {
System.out.println("Parameterized constructor called!");
// Use 'this' keyword to distinguish instance variables from local parameters
this.name = dogName;
this.age = dogAge;
}
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Must provide matching parameters when creating object
Dog myDog = new Dog("Buddy", 3);
myDog.displayInfo(); // Output: Name: Buddy, Age: 3
// Dog anotherDog = new Dog(); // This line will cause compile error, as default constructor no longer exists
}
}The this Keyword
In the example above, the line this.name = dogName;:
this.namerefers to the instance variablenameof the current object being created.dogNamerefers to the local parameterdogNamepassed to the constructor.
When parameter names and instance variable names are the same, you must use the this keyword to disambiguate. This is a very common coding style.
Constructor Overloading
Like regular methods, constructors can also be overloaded. This means a class can have multiple constructors, as long as their parameter lists are different (different in number, type, or order of parameters).
This provides greater flexibility for creating objects.
public class Employee {
String name;
String department;
double salary;
// Constructor 1: Only provide name, department and salary use default values
public Employee(String name) {
this.name = name;
this.department = "Unassigned";
this.salary = 3000.0;
}
// Constructor 2: Provide name and department
public Employee(String name, String department) {
this.name = name;
this.department = department;
this.salary = 3000.0;
}
// Constructor 3: Provide all information
public Employee(String name, String department, double salary) {
this.name = name;
this.department = department;
this.salary = salary;
}
public void display() {
System.out.printf("Name: %s, Department: %s, Salary: %.2f%n", name, department, salary);
}
}
public class Main {
public static void main(String[] args) {
Employee emp1 = new Employee("John");
Employee emp2 = new Employee("Jane", "Tech");
Employee emp3 = new Employee("Bob", "Marketing", 8000.0);
emp1.display();
emp2.display();
emp3.display();
}
}By overloading constructors, we can conveniently create objects that meet requirements based on different initial information.