Practice 1: Instantiable Classes
Write a class called Fountain
. Objects of
this class will have three component variables:
- the capacity of the fountain (in liters),
- the amount of water currently in the fountain (also in liters), and
- whether the fountain is currently running or not.
Fountains start out empty, in the off
state, with a given capacity.
For example,
Fountain fountain = new Fountain(200);
should create a Fountain
object representing an empty
fountain which is not running and has a capacity of 200 liters of
water.
Besides the constructor, you will need three additional methods:
add(int liters)
, toggle()
, and look()
.
Here is a sample Main class in Java that tests the fountain.
public class Main {
public static void main(String[] args) {
Fountain f = new Fountain(200);
System.out.println(f.look());
f.toggle();
System.out.println(f.look());
f.add(120);
System.out.println(f.look());
f.toggle();
System.out.println(f.look());
f.add(397);
System.out.println(f.look());
f.toggle();
System.out.println(f.look());
f.toggle();
System.out.println(f.look());
f.add(-90);
System.out.println(f.look());
f.add(-200);
System.out.println(f.look());
}
}
When you run the above code, here is a sample of output that you could see.
Your implementation does not have to produce exactly the same messages, as
long as they contain the same information.
The fountain is off. It contains 0 liters of water.
The fountain is off. It contains 0 liters of water.
The fountain is off. It contains 120 liters of water.
Sploosh! The fountain is on. It contains 120 liters of water.
Sploosh! The fountain is on. It contains 200 liters of water.
The fountain is off. It contains 200 liters of water.
Sploosh! The fountain is on. It contains 200 liters of water.
Sploosh! The fountain is on. It contains 110 liters of water.
The fountain is off. It contains 0 liters of water.