Are Multiple Constructors possible in Java?



Constructors in Java are special methods that are used to initialize objects. In Java, it is possible to have multiple constructors in a class; this is known as constructor overloading.

So, the answer to the question "Are multiple constructors possible in Java?" is yes, Java allows multiple constructors in a class. This feature is useful for creating objects in different ways, depending on the parameters passed during object creation. Parameters should be different in type or number to distinguish between the constructors.

Example of Multiple Constructors in Java

In this example, we will create a class named `Book` with multiple constructors. Each constructor will initialize the object in different ways based on the parameters provided.

public class Book {
   String title;
   String author;
   double price;

   // Constructor with all parameters
   public Book(String title, String author, double price) {
      this.title = title;
      this.author = author;
      this.price = price;
   }
   // Constructor with title and author, default price
   public Book(String title, String author) {
      this.title = title;
      this.author = author;
      this.price = 9.99; // default price
   }
   // Constructor with title only, default author and price
   public Book(String title) {
      this.title = title;
      this.author = "Unknown"; // default author
      this.price = 9.99; // default price
   }
   // Method to display book details
   public void display() {
      System.out.println("Title: " + title);
      System.out.println("Author: " + author);
      System.out.println("Price: $" + price);
   }
   public static void main(String[] args) {
      // Creating objects using different constructors
      Book book1 = new Book("Effective Java", "Joshua Bloch", 45.00);
      Book book2 = new Book("Clean Code", "Robert C. Martin");
      Book book3 = new Book("Java: The Complete Reference");

      // Displaying book details
      book1.display();
      System.out.println();
      book2.display();
      System.out.println();
      book3.display();
   }
}    

In this example, the `Book` class has three constructors:

Title: Effective Java
Author: Joshua Bloch
Price: $45.0

Title: Clean Code
Author: Robert C. Martin
Price: $9.99

Title: Java: The Complete Reference
Author: Unknown
Price: $9.99

In this article, learn how to create multiple constructors in Java and how they can be used to initialize objects in different ways.

Aishwarya Naglot
Aishwarya Naglot

Writing clean code… when the bugs aren’t looking.

Updated on: 2020-06-30T08:45:40+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements