Object oriented programming rests on a few big ideas. The first is encapsulation. An object hides its details, and offers a small, safe set of methods instead.
The temperature is a private field. Other code can read it in Celsius, or in Fahrenheit. Fahrenheit isn't even stored. It's worked out when asked. And set Celsius only accepts sensible values, from five to thirty.
Main.javajava
public class Thermostat { private double celsius = 20; public double getCelsius() { return celsius; } public double getFahrenheit() { return celsius * 9 / 5 + 32; } public void setCelsius(double c) { if (c < 5 || c > 30) { System.out.println("Refused: " + c + " is outside 5-30"); return; } celsius = c; }}
We set twenty two point five, which is accepted. Then eighty, which is refused. Run it. The thermostat protects itself. And it reports seventy two point five Fahrenheit.
Main.javajava
public class Main { public static void main(String[] args) { Thermostat t = new Thermostat(); t.setCelsius(22.5); t.setCelsius(80); System.out.println(t.getCelsius() + " C = " + t.getFahrenheit() + " F"); }}
Output
Refused: 80.0 is outside 5-30
22.5 C = 72.5 F
Also uses Thermostat.java
public class Thermostat { private double celsius = 20; public double getCelsius() { return celsius; } public double getFahrenheit() { return celsius * 9 / 5 + 32; } public void setCelsius(double c) { if (c < 5 || c > 30) { System.out.println("Refused: " + c + " is outside 5-30"); return; } celsius = c; }}
Other code can't put the object into a broken state. The inside can change, without breaking anyone. Users only need to learn a few methods. And bugs are easier to find, because all changes go through one place.