Homework help! Consider the Creature class: public class Creature { private Stri
ID: 3702968 • Letter: H
Question
Homework help!
Consider the Creature class:
public class Creature {
private String name;
private String weapon;
private double lifeLevel;
public Creature(String name, String weapon) {
this.name = name;
this.weapon = weapon;
lifeLevel=100;
}
public String getName(){return name;}
public String getWeapon(){return weapon;}
public double getLifeLevel(){return lifeLevel;}
public void die(){lifeLevel = 0;}
public boolean isAlive(){return (lifeLevel>0);}
/* Adds the argument: incAmt to the lifeLevel.
* Note: if the lifeLevel is currently 0 it should not change
*/
public void updateLifeLevel(double incAmt){
if(lifeLevel > 0)
lifeLevel += incAmt;
}
public String speak(){
return " ";
}
public String toString() {
return name+", weapon: "+weapon+", life level: "+lifeLevel;
}
}
Question 4.
Create a subclass of the Creature class called the Troll class. A Troll has the following attribute in addition to a Creature:
• happinessLevel a double representing how happy the Troll is.
This attribute is initialized in the Troll's constructor, which you must write.
ANSWER
//Declare the class header
//Declare and initialize variable
//Write the constructor
Explanation / Answer
//Declare the class header
class Troll:public Creature
{};
//Declare and initialize variable
class Troll:public Creature
{
private double happinessLevel;
public double get_happinessLevel()
{
return happinessLevel;
}
public Creature(int happinessLevel)
{
happinessLevel=100;
}
};
//Write the constructor
Troll(int happinessLevel)
{
this.happinessLevel=happinessLevel;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.