PLEASE HELP!! NEED HELP!! 5 stars for correct answer! 1. Write a class called Ca
ID: 3555420 • Letter: P
Question
PLEASE HELP!! NEED HELP!! 5 stars for correct answer!
1. Write a class called Candy. Include private double variables called "weight", and "calories". Include
getter and setter methods for these. Also include a toString method that properly returns a string version
of the weight and calories.
2. Write a subclass of Candy called "HardCandy". Include a private int variable called "hardness". Include
a getter and setter for hardness. Include a toString method that returns a string representation of the
calories, weight, and hardness of the candy.
3. Write a subclass of Candy called "Chocolate". Include a private double variable called "cocoaFraction".
Include a getter and setter for the cocoa fraction. Include a toString method that returns a string
representation of the calories, weight, cocoa fraction of the chocolate.
Explanation / Answer
class Candy
{
private double weight;
private double calories;
Candy(double weight,double calories)
{
this.weight=weight;
this.calories=calories;
}
public void setWeight(double w)
{
weight=w;
}
public void setCalories(double c)
{
calories=c;
}
public double getWeight()
{
return weight;
}
public double getCalories()
{
return calories;
}
public String toString()
{
return "Weight:"+weight+" ,Calories:"+calories;
}
}
class HardCandy extends Candy
{
private int hardness;
HardCandy(double weight,double calories,int hardness)
{
super(weight,calories);
this.hardness=hardness;
}
public void setHardness(int h)
{
hardness=h;
}
public int getHardness()
{
return hardness;
}
public String toString()
{
return "Weight:"+getWeight()+" ,Calories:"+getCalories()+", Hardness:"+hardness;
}
}
class Chocolate extends Candy
{
private double cocoaFraction;
Chocolate(double weight,double calories,double cocoaFraction)
{
super(weight,calories);
this.cocoaFraction=cocoaFraction;
}
public void setCocoaFraction(double c)
{
cocoaFraction=c;
}
public double getCocoaFraction()
{
return cocoaFraction;
}
public String toString()
{
return "Weight:"+getWeight()+" ,Calories:"+getCalories()+", Cocoafraction:"+cocoaFraction;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.