Files
oop/lab/lab4/Question4/Chicken.java
2022-03-17 18:18:06 +08:00

93 lines
2.0 KiB
Java

/*
* Author: CHEN Yongyuan (Walter) 1930006025 from OOP(1007)
* Date: 2022-03-17
* Description: This is the Chicken class.
*/
public class Chicken {
/*
* The weight instance variable indicates the current weight of the chiken.
*/
private double weight;
/*
* The sleeping instance variable indicates whether the chicken is currently
* sleeping or not.
* It is intially sleeping.
*/
private boolean sleeping;
/**
* Constructor: Chicken(double weight)
*
* @param weight
* The weight of the chicken.
* The weight must be greater than 0. If the weight is less than
* 0, the weight is set to 0.
*/
public Chicken(double weight) {
if (weight < 0) {
this.weight = 0;
} else {
this.weight = weight;
}
// initially the chicken is sleeping
this.sleeping = true;
}
/**
* Getter method: getWeight()
*
* @return The weight of the chicken.
*/
public double getWeight() {
return this.weight;
}
/**
* Getter method: isSleeping()
*
* @return true if the chicken is sleeping, false otherwise.
*/
public boolean isSleeping() {
return this.sleeping;
}
/**
* Makes the chicken fall asleep. Or do nothing if the chicken is already
* sleeping.
*
* @return void
*/
public void fallAsleep() {
this.sleeping = true;
}
/**
* Makes the chicken wake up. Or do nothing if the chicken is already awake.
*
* @return void
*/
public void wakeUp() {
this.sleeping = false;
}
/**
* Tests function.
*/
public static void testChicken() {
Chicken c = new Chicken(2.3);
System.out.println(c.getWeight() == 2.3);
System.out.println(c.isSleeping() == true);
c.wakeUp();
System.out.println(c.isSleeping() == false);
c.wakeUp(); // should do nothing because the chicken is already awake
System.out.println(c.isSleeping() == false);
c.fallAsleep();
System.out.println(c.isSleeping() == true);
c.fallAsleep(); // should do nothing because the chicken is already sleeping
System.out.println(c.isSleeping() == true);
}
}