AI Hints
Home›Java Tutorial›Encapsulation, Inheritance and super
Java · Lesson 73 of 120

Encapsulation

Hide the details.

⏱ 2 min read▶ Video at 1:31:42🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

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.

  • Big idea one
  • Hide the details
  • Offer safe methods

A thermostat

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;
    }
}

Using it safely

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;
    }
}

Why encapsulation

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.

keyvalue
Safeno broken states
Flexiblechange the inside freely
Simplea few public methods
Debuggableone way in

Summary

Encapsulation means private fields, and a few public methods that protect them. Next, the second big idea, inheritance.

Key takeaways
  • Private data
  • Public methods
  • Validated changes
Next up: Inheritance — build on another class