Create a program that shows constructor overloading in Java
The Box class in Java represents a simple box with three dimensions: width, height, and depth. It contains two constructors: a default constructor that initializes the dimensions to 1, and a parameterized constructor that allows you to specify the dimensions during object creation. Additionally, it has a method called myMethod() that prints the dimensions of the box. In the main method, we demonstrate creating instances of the Box class using both constructors and print the dimensions of one of the boxes. This class provides a basic example of object-oriented programming principles in Java, including constructors, instance variables, and methods.
class Box { double width, height, depth; Box() { width = 1; height = 1; depth = 1; } Box(double w, double h, double d) { width = w; height = h; depth = d; } void myMethod() { System.out.println("Width : " + width); System.out.println("Height : " + height); System.out.println("Depth : " + depth); } public static void main(String[] args) { Box box1 = new Box(); Box box2 = new Box(3, 8, 6); box2.myMethod(); } }
Width : 3.0 Height : 8.0 Depth : 6.0
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions