Implement a class called GroceryItem that represents grocery items that one woul
ID: 3786253 • Letter: I
Question
Implement a class called GroceryItem that represents grocery items that one would pick up when doing your supermarket shopping. The class has 4 private instance variables: name of type String representing the name of the item (e.g. "Cascade") price of type float representing the cost of the item (e.g., $4.79) weight of type float representing the weight of the item in Kilograms (e.g., 2.4 kg) perishable of type boolean. A value of true indicates that the item needs to be refrigerated or frozen and false otherwise. Implement the following instance methods: public get methods for the attributes. A zero-argument constructor A constructor that accepts as arguments the item's name, price and weight. Note that the perishable variable is not indicated here. It should be set to false by default. Make another constructor to accept all 4 parameters, perishable being one of them. A toString() method that returns a string representation of the item like this: "Cascade weighing 2.4kg with price $7.9"Explanation / Answer
Hi, Please find my implementtion.
Please let me know in case of any issue.
public class GroceryItem {
// instance variables
private String name;
private float price;
private float weight;
private boolean perishable;
// constructors
public GroceryItem() {
name = "";
price = 0;
weight = 0;
perishable = false;
}
public GroceryItem(String name, float price, float weight, boolean perishable) {
this.name = name;
this.price = price;
this.weight = weight;
this.perishable = perishable;
}
public GroceryItem(String name, float price, float weight) {
this.name = name;
this.price = price;
this.weight = weight;
perishable = false;
}
// getters and setters methods
public String getName() {
return name;
}
public float getPrice() {
return price;
}
public float getWeight() {
return weight;
}
public boolean isPerishable() {
return perishable;
}
@Override
public String toString() {
return name+" weighing "+weight+"kg with price $"+price;
}
// main method
public static void main(String[] args) {
GroceryItem grocery = new GroceryItem("Cascade", 4.79f, 2.4f);
System.out.println(grocery);
}
}
/*
Sample run:
Cascade weighing 2.4kg with price $4.79
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.