In: Computer Science
Question1: Consider the below description of the class Box. 1. Create a class and call it Box. Box has the following methods & variables a. Variable for length, height, width & volume, b. setlength(int x ) method to set the length, c. setWidth (int y ) method to set the width, d. setHeight (int z ) method to set the height & e. displayCalculatedVolume( ) method that calculates the volume and displays it. (Hint: volume = length*width*height)
Answer:
Here is the code, please go through the comments for better understanding of the code. Drop me a comment if you have any doubts, I'll be glad to help you. All you have to do is to create a class called Box.java, paste the below code and run, Enjoy!
Box.java
public class Box { // start of class
// attributes of the box
private int length;
private int height;
private int width;
private int volume;
public void setLength(int length) { // this method sets the
length
this.length = length;
}
public void setHeight(int height) { // this method sets the
height
this.height = height;
}
public void setWidth(int width) { // this method sets the
width
this.width = width;
}
public void displayCalculatedVolume(){ // this method calculates
the volume
volume = length*width*height;
System.out.println("The volume of the box : " + volume); //
displaying the volume
}
public static void main(String [] args){ // start of main()
Box b = new Box(); // create an instance of class Box
b.setLength(10); // call the method setLength() with some int
value
b.setHeight(8); // call the method setHeight() with some int
value
b.setWidth(5); // call the method setWidth() with some int
value
b.displayCalculatedVolume(); // calculates the volume with the
given values
} // end of main()
} // end of class
Output's screenshot