Experiment 2 - Constructor Overloading
Aim
Demonstrate constructor overloading by implementing a class (such as Book) with multiple
constructors to demonstrate different initialization behaviors.
Theory
Constructor overloading allows a class to have multiple constructors with different parameter
lists. The this() keyword can be used to call another constructor in the same class, enabling
constructor chaining. This technique helps avoid code duplication and ensures consistent
initialization. Constructor overloading is useful when objects need to be initialized in different
ways depending on the available information. The Java compiler distinguishes constructors
by their parameter types and count.
Input/Parameter Used
(1) title: String - represents the title of the book
(2) author: String - represents the author of the book
(3) price: double - represents the price of the book (must be >= 0)
(4) Default constructor: initializes with "Unknown", "Unknown", 0.0
(5) Two-parameter constructor: accepts title and author
(6) Three-parameter constructor: accepts title, author, and price
Procedure/Algorithm
Step 1: Create a Book class with private fields title, author, and price
Step 2: Implement a default constructor that uses this() to call the three-parameter
constructor with default values
Step 3: Implement a two-parameter constructor that uses this() to call the three-parameter
constructor with price as 0.0
Step 4: Implement a three-parameter constructor that directly initializes all fields
Step 5: Create a display() method to show book details
Step 6: In the main method, create Book objects using different constructors
Step 7: Display all book objects to demonstrate different initialization behaviors
Program/Code:
class Book {
private String title;
private String author;
private double price;
public Book() {
this("Unknown", "Unknown", 0.0);
}
public Book(String title, String author) {
this(title, author, 0.0);
}
public Book(String title, String author, double price) {
[Link] = title;
[Link] = author;
[Link] = price;
}
public void display() {
[Link]("Title: %s, Author: %s, Price: %.2f%n", title, author, price);
}
}
public class ConstructorOverloadingDemo {
public static void main(String[] args) {
Book b1 = new Book();
Book b2 = new Book("Core Java", "Horstmann", 270.0);
Book b3 = new Book("Effective Java", "Joshua Bloch", 450.0);
[Link]();
[Link]();
[Link]();
}
}
Conclusion
This experiment successfully demonstrated constructor overloading in Java. We learned
how multiple constructors can be defined with different parameter lists to provide flexible
object initialization. The use of this() for constructor chaining helped avoid code duplication
and ensured consistent initialization. This technique is essential in object-oriented
programming for creating objects with varying levels of detail.