In this lesson, you will learn
class Box {
private double width;
private double height;
private double depth;
// Constructor 1: All dimensions
public Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
// Constructor 2: Width and height (depth defaults to 1)
public Box(double width, double height) {
this.width = width;
this.height = height;
this.depth = 1;
}
// Constructor 3: Width only (height and depth default to 1)
public Box(double width) {
this.width = width;
this.height = 1;
this.depth = 1;
}
public double getVolume() {
return width * height * depth;
}
public void displayDimensions() {
System.out.println("Width: " + width + ", Height: " + height + ", Depth: " + depth);
}
}
public class ConstructorOverloadingExample1 {
public static void main(String[] args) {
Box box1 = new Box(10, 5, 2); // Uses constructor 1
Box box2 = new Box(8, 6); // Uses constructor 2
Box box3 = new Box(7); // Uses constructor 3
box1.displayDimensions();
System.out.println("Volume: " + box1.getVolume());
box2.displayDimensions();
System.out.println("Volume: " + box2.getVolume());
box3.displayDimensions();
System.out.println("Volume: " + box3.getVolume());
}
}
Width: 10.0, Height: 5.0, Depth: 2.0
Volume: 100.0
Width: 8.0, Height: 6.0, Depth: 1.0
Volume: 48.0
Width: 7.0, Height: 1.0, Depth: 1.0
Volume: 7.0
class Product {
private String name;
private int productId;
private double price;
// Constructor 1: All parameters
public Product(String name, int productId, double price) {
this.name = name;
this.productId = productId;
this.price = price;
}
// Constructor 2: Name and price (productId defaults to -1)
public Product(String name, double price) {
this.name = name;
this.productId = -1; // Default product ID
this.price = price;
}
// Constructor 3: Name and productId (price defaults to 0.0)
public Product(String name, int productId) {
this.name = name;
this.productId = productId;
this.price = 0.0;
}
public void displayProductInfo() {
System.out.println("Name: " + name + ", ID: " + productId + ", Price: $" + price);
}
}
public class ConstructorOverloadingExample2 {
public static void main(String[] args) {
Product product1 = new Product("Laptop", 12345, 1200.0);
Product product2 = new Product("Mouse", 25.0);
Product product3 = new Product("Keyboard", 67890);
product1.displayProductInfo();
product2.displayProductInfo();
product3.displayProductInfo();
}
}
Name: Laptop, ID: 12345, Price: $1200.0
Name: Mouse, ID: -1, Price: $25.0
Name: Keyboard, ID: 67890, Price: $0.0
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.