In: Computer Science
JAVA: Lab11C:Behaviors.In the context of OOP, functions are called methods or behaviors because they typically do something. Most often, they read or change the values of one or more variables in the class. For example, you may have a weight variable in a class, and a method called gainWeight( ) that increases the weight variable by a certain amount.
For this part of the lab, create class KoalaBear that has a weightattribute(in kilograms). Create a constructor for the class that takes in (as a parameter) the initial weight of the koala bear. Then, write a function called eat( ) that takes in the number of leaves the koala bear should eat. Each leaf weighs one gram, so you must increase the weight of the koala bear by one gram. According to a site dedicated to saving Koala bears, they can eat between 200-500 grams of leaves per day. To finish the class out, include a showWeight() method that prints out how much the koala weighs.
In main, create a koala object starting at 100 kilos and show the koala’s weight. Then, make the koala eat 400, 300, and 650 leaves, showing the weight of the koala after each time it eats.
NOTE: if you’re output does not match exactly (because of the rounding of floating point math), that’s OK. For example, Java will include some extra “precision”.
Sample output #1
This koala weighs 100.4 kilos
This koala weighs 100.7 kilos
This koala weighs 101.35 kilos
public class KoalaBear {
private double weight; //attribute
// constructor
public KoalaBear(double weight) {
this.weight =
weight;
}
//method that takes in the number of leaves the
koala bear should eat
public void eat(int n){
double gainedWeight =
n/1000.0;
this.weight +=
gainedWeight;
}
//method that prints out how much the koala
weighs.
public void showWeight(){
System.out.printf("This
koala weighs %.2f kilos\n",this.weight);
}
//main method
public static void main(String[] args) {
KoalaBear koala = new
KoalaBear(100);
koala.eat(400);
koala.showWeight();
koala.eat(300);
koala.showWeight();
koala.eat(650);
koala.showWeight();
}
}
Sample output