Fill in the blanks to complete the Java code based on the following description, UML Class Diagram and comments:
Class:
- Barrel
Field/attribute:
- String contents
- double amount
- double radius
- double height
Methods:
- Barrel (String newContents, double newAmount, double newRadius, double newHeight)
- double calculateCapacity()
- void fill(double newAmount)
- String display()
Above describes the UML class diagram for a Barrel object.
The UML is based on Barrel class. A Barrel is a cylindrical container. The program calculates the capacity of the barrel. The barrel can be filled with any content.
The constructor should initialize the appropriate instance variables.
The program also displays the content type, capacity, and current amount of content in the barrel.
Below is the expected result / sample output:
This barrel contains Oil. It’s capacity is 282.60 and it contains 70.0 litres
##########After Fill##########
This barrel contains Oil. It’s capacity is 282.60 and it contains 115.0 litres
Here is the Java code:
public class Barrel {
// fields
private String contents;
private double amount; // 2 points
private double radius; // 2 points
private double height;
// Declare a constant named PI and set its value to 3.14
private final double PI = 3.14; // 2 points
public Barrel(String newcontents, double newAmount, double newRadius, double newHeight) {
contents = newcontents //2 points
amount = newAmount;
radius = newRadius;
height = newHeight; //2 points
}
// calculateCapacity() method should return the area of the barrel (area of one end * height)
public double calculateCapacity() {
return PI * radius * radius * height; // 2 points
}
// The fill() method should set amount to the existing amount + newAmount
public void fill(double newAmount) {
amount = amount + newAmount //2 points
}
// the display method returns the Barrel details
public String display() {
return “This barrel contains ” + contents + “. It’s capacity is ” + calculateCapacity() + ” and it contains ”
+ amount + ” litres”;
}
}
// Tester class with main method
public class BarrelTester {
public static void main(String args) {
// Declare the reference variable of Barrel
Barrel barrel; // 2 points
barrel = new Barrel(“Oil”, 70, 3, 10);
// Display the Barrel contents and its amount, and capacity
System.out.println(barrel.display()); // 2 points
// fill barrel with 45 more litres of diesel
barrel.fill(45); // 2 points
System.out.println(“##########After Fill##########”);
System.out.println(barrel.display());
}
}