Write a class called Shelf that contains instance data that represents the lengt
ID: 3923832 • Letter: W
Question
Write a class called Shelf that contains instance data that represents the length, breadth, and capacity of the shelf. Also include a boolean variable called occupied as instance data that represents whether the shelf is occupied or not. Define the Shelf constructor to accept and initialize the height, width, and capacity of the shelf. Each newly created Shelf is vacant (the constructor should initialize occupied to false). Include getter and setter methods for all instance data. Include a toString method that returns a one-line description of the shelf. Create a driver class called ShelfCheck, whose main method instantiates and updates several Shelf objects. (Java)
Explanation / Answer
Shelf.java
public class Shelf {
private double length;
private double breadth;
private int capacity ;
private boolean occupied ;
public Shelf(double length, double breath ,int capacity){
this.length = length;
this.breadth = breath;
this.capacity = capacity;
occupied = false;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getBreadth() {
return breadth;
}
public void setBreadth(double breadth) {
this.breadth = breadth;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public boolean isOccupied() {
return occupied;
}
public void setOccupied(boolean occupied) {
this.occupied = occupied;
}
public String toString(){
return "Length: "+getLength()+" Breadth: "+getBreadth()+" Capacity: "+getCapacity()+" Occupied: "+isOccupied();
}
}
ShelfCheck.java
public class ShelfCheck {
public static void main(String[] args) {
Shelf s = new Shelf(10,20, 5);
System.out.println(s.toString());
s.setOccupied(true);
System.out.println(s.toString());
s.setBreadth(50);
s.setLength(30);
s.setCapacity(40);
s.setOccupied(true);
System.out.println(s.toString());
}
}
Output:
Length: 10.0 Breadth: 20.0 Capacity: 5 Occupied: false
Length: 10.0 Breadth: 20.0 Capacity: 5 Occupied: true
Length: 30.0 Breadth: 50.0 Capacity: 40 Occupied: true
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.