Today you will be given a FruitFruit class. From this, you will create a new cla
ID: 3908784 • Letter: T
Question
Today you will be given a FruitFruit class. From this, you will create a new class FruitBasket that will store fruit objects in a basket.
The Fruit class has the following fields:
name (String) : name of the fruit
colour (String) : colour of the fruit’s skin
It has a constructor and five methods, including a toString()toString() method, 2 getters and 2 setters. Details follow.
import java.util.*;
public class FruitBasket
{
public String toString()
{
String basketContents = "FRUIT BASKET: ";
for (Fruit fruit: basket)
{
basketContents += fruit.toString()+" ";
}
return basketContents;
}
}
Fruit class Fruit #name : String #colour : String +getName) : String Returns the value of the field name +getColour String Returns the value of the field colour +setName) : String Sets the value of name +setColour): String Sets the value of colour +toStringO String Returns details of the Fruit object.Explanation / Answer
Fruit class:
//Fruit class-STARTS
public class Fruit
{
//data members
private String name,colour;
//default construtor
public Fruit() {}
//parametrized construtor
public Fruit(String name,String colour)
{
this.name=name;
this.colour=colour;
}
//getter and setter methods
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
//toString() method
public String toString()
{
return name+" (" + colour+ ")";
}
}
//Fruit class-ENDS
FruitBasket class:
import java.util.*;
//FruitBasket class-STARTS
public class FruitBasket
{
//attribute basket
List<Fruit> basket=null;
//Constructor to initialize the ArrayList
public FruitBasket()
{
basket=new ArrayList<Fruit>();
}
//method to addFruit()
public void addFruit(Fruit fruit)
{
basket.add(fruit);
}
//toString() method
public String toString()
{
String basketContents = "FRUIT BASKET: ";
for(Fruit fruit: basket)
{
basketContents += fruit.toString()+" ";
}
return basketContents;
}
}
//FruitBasket class-ENDS
main class:
public class PoD
{
public static void main(String[]arg)
{
//creating Fruit objects
Fruit red= new Fruit("apple","red");
Fruit green= new Fruit("pear","green");
//FruitBasket object
FruitBasket fb = new FruitBasket();
//adding objects
fb.addFruit(red);
fb.addFruit(green);
//calling toString()
System.out.println(fb.toString());
}
}