In Java, a constructor is a special type of method used to initialize objects when they are created. It is automatically invoked when an object of a class is created. Constructors play a crucial role in setting up initial values for object attributes and ensuring that objects are properly initialized before use.
In this guide, we'll explore Java constructors in detail, covering their types, syntax, how they work, and examples to help you understand their usage.
this
KeywordA constructor in Java is a block of code used to initialize an object. When an object is created using the new
keyword, the constructor is automatically invoked to set up initial values for the object's properties (instance variables). Constructors do not have a return type and their name must be the same as the class name.
void
.new
keyword.In Java, constructors can be broadly classified into two types:
class ClassName {
// Constructor
public ClassName() {
// Initialization code
}
}
class ClassName {
// Constructor with parameters
public ClassName(parameter1, parameter2, ...) {
// Initialization code
}
}
Let's look at a basic example of using a constructor to initialize an object.
public class Car {
// Instance variables
String model;
int year;
// Constructor to initialize the object
public Car(String model, int year) {
this.model = model;
this.year = year;
}
// Method to display car details
public void display() {
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
// Create a Car object and pass values to the constructor
Car myCar = new Car("Toyota Corolla", 2020);
// Call the display method to show car details
myCar.display();
}
}
Output:
Model: Toyota Corolla
Year: 2020
In this example, the Car
class has a parameterized constructor that takes two parameters (model
and year
). When the object myCar
is created, the constructor is called to initialize these values.
A default constructor is a constructor that doesn't take any parameters. If you do not explicitly define a constructor, Java provides a default constructor with no arguments. This constructor initializes the instance variables with default values (e.g., 0
for numeric types, null
for object references).
public class Book {
String title;
String author;
// Default constructor
public Book() {
title = "Unknown";
author = "Unknown";
}
// Method to display book details
public void display() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
}
}
public class Main {
public static void main(String[] args) {
// Create a Book object using the default constructor
Book myBook = new Book();
// Call the display method to show book details
myBook.display();
}
}
Output:
Title: Unknown
Author: Unknown
In this example, since the Book
class doesn't have a parameterized constructor, Java provides a default constructor that initializes the title
and author
fields to "Unknown".
A parameterized constructor allows you to pass arguments when creating an object. This helps initialize the object with specific values.
public class Laptop {
String brand;
double price;
// Parameterized constructor
public Laptop(String brand, double price) {
this.brand = brand;
this.price = price;
}
// Method to display laptop details
public void display() {
System.out.println("Brand: " + brand);
System.out.println("Price: " + price);
}
}
public class Main {
public static void main(String[] args) {
// Create a Laptop object using the parameterized constructor
Laptop myLaptop = new Laptop("Dell", 799.99);
// Call the display method to show laptop details
myLaptop.display();
}
}
Output:
Brand: Dell
Price: 799.99
In this example, the Laptop
class has a parameterized constructor that accepts the brand
and price
as arguments.
Constructor overloading is similar to method overloading. It allows you to define multiple constructors with different parameter lists. This provides flexibility in object creation.
public class Smartphone {
String brand;
double price;
// Constructor with no parameters
public Smartphone() {
brand = "Unknown";
price = 0.0;
}
// Constructor with one parameter
public Smartphone(String brand) {
this.brand = brand;
price = 0.0;
}
// Constructor with two parameters
public Smartphone(String brand, double price) {
this.brand = brand;
this.price = price;
}
// Method to display smartphone details
public void display() {
System.out.println("Brand: " + brand);
System.out.println("Price: " + price);
}
}
public class Main {
public static void main(String[] args) {
// Create objects using different constructors
Smartphone phone1 = new Smartphone();
Smartphone phone2 = new Smartphone("Samsung");
Smartphone phone3 = new Smartphone("Apple", 999.99);
phone1.display();
phone2.display();
phone3.display();
}
}
Output:
Brand: Unknown
Price: 0.0
Brand: Samsung
Price: 0.0
Brand: Apple
Price: 999.99
In this example, we overloaded the constructor to provide different ways of initializing the Smartphone
object.
this
KeywordIn Java, the this
keyword is used inside a constructor to refer to the current object. It is commonly used when the parameter name is the same as the instance variable name to differentiate between them.
this
Keyword
public class Person {
String name;
int age;
// Constructor with 'this' keyword to distinguish between instance variables and parameters
public Person(String name, int age) {
this.name = name; // Assign the parameter value to the instance variable
this.age = age; // Assign the parameter value to the instance variable
}
// Method to display person details
public void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Create a Person object
Person person = new Person("John", 30);
// Call the display method to show details
person.display();
}
}
public class Main {
public static void main(String[] args) {
// Create a Person object
Person person = new Person("John", 30);
// Call the display method to show details
person.display();
}
}
Output:
Name: John
Age: 30
Here, the this
keyword differentiates between the instance variables name
and age
and the parameters passed to the constructor.
Constructor chaining refers to the technique of calling one constructor from another constructor in the same class or in a superclass. This can help avoid code duplication and improve readability.
public class Animal {
String name;
// Constructor of Animal class
public Animal(String name) {
this.name = name;
}
}
public class Dog extends Animal {
// Constructor of Dog class
public Dog(String name) {
// Calling the constructor of the superclass (Animal)
super(name);
}
// Method to display dog details
public void display() {
System.out.println("Dog's name: " + name);
}
}
public class Main {
public static void main(String[] args) {
// Create a Dog object
Dog dog = new Dog("Buddy");
// Call the display method to show details
dog.display();
}
}
Output:
Dog's name: Buddy
In this example, the constructor of the Dog
class calls the constructor of the Animal
class using super(name)
to initialize the name
attribute.