Q:

programming2 java course exam question | OOP and inheritance

0

Define superclass Food that has the following specifications:

private instance variables:

- name which is the food name of type String.

public methods:

- full-argument constructor to initialize the instantiated objects.

- toString() to return food data.

Define subclass SeaFood that inherits the class Food and has the following specifications:

private instance variables:

- pricePerKilo which is the price per kilo of type double.

- quantity which is the quantity in kilos of type int.

public methods:

- full-argument constructor (receives three paramers: name, price and quantity)

- toString() to return food data and seafood data.

- main method that create an array of three objects of type SeaFood. Fill them with data. Print data of all seafood objects and their total price [Total is computed as summation of price×quantity for all objects].

Sample of output:

Name: Shrimp, Price/kg: 60.0 SAR, Quantity: 4 kg

Name: Salmon, Price/kg: 50.0 SAR, Quantity: 5 kg

Name: Tuna, Price/kg: 30.0 SAR, Quantity: 2 kg

Total price: 550.0 SAR

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

class Food {
 private String name; //0.25
 public Food(String name) { //0.25
 this.name = name;
 }
 public String toString() { //0.25
 return "Name: " + name;
 }
}
public class SeaFood extends Food { //0.5
 private double pricePerKilo; //0.25
 private int quantity; //0.25
 public SeaFood(String name, double price, int qty) { //0.75; 0.25 for 
super
 super(name);
 pricePerKilo = price;
 quantity = qty;
 }
 public String toString() { //0.5; 0.25 for super
 return super.toString() + ", Price/kg: " + pricePerKilo + " SAR, 
 Quantity: "+ quantity + " kg";
 }
 public static void main(String[] args) {
 double total = 0.0;
 SeaFood sf[] = new SeaFood[3]; //0.5
 sf[0] = new SeaFood("Shrimp", 60, 4); //0.5; for 3 objects
 sf[1] = new SeaFood("Salmon", 50, 5);
sf[2] = new SeaFood("Tuna", 30, 2);
 for (SeaFood item : sf) { //0.5
 System.out.println(item); //0.25
 total += (item.pricePerKilo*item.quantity); //0.5
 }
 System.out.println("Total price: " + total + " SAR"); //0.25
 }
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now