• Lessons Home
Topics
Community
  1. Lessons
  2. Object-Oriented Apex
  3. Classes and Objects
  4. Encapsulation

      Encapsulation

      Encapsulation

      So far every field has been public, which means any code anywhere can change it to anything. Nothing stops other code from writing thermostat.temperature = 500;. Encapsulation is the habit of hiding the data of an object and only letting the outside world change it through methods that enforce the rules.

      Private Fields, Public Methods

      Mark the field private so only code inside the class can touch it, then add public methods that are the only way in:

      public class Thermostat {
      	private Integer temperature = 20;
      
      	public Integer getTemperature() {
      		return temperature;
      	}
      
      	public void setTemperature(Integer value) {
      		if (value >= 10 && value <= 30) {
      			temperature = value;
      		}
      	}
      }
      

      Code outside the class reads the temperature through getTemperature(), and the only way to change it is setTemperature(), which ignores anything outside 10 to 30. The object can never hold a bad value.

      Methods That Report Back

      A method that might refuse a change can return a Boolean so the caller knows what happened:

      public Boolean raise(Integer degrees) {
      	if (temperature + degrees > 30) {
      		return false;
      	}
      	temperature = temperature + degrees;
      	return true;
      }
      

      Apex Properties

      Apex also has a shorthand for a field with a getter and a setter, called a property:

      public Integer temperature { get; private set; }
      

      Any code can read temperature, but only code inside the class can set it.

      A Note on the Exercise Editor

      In a real org, reading a private field from another class is a compile error. The exercise editor runs all of your code together in one block, where Apex is more forgiving about private, so treat the rule as a promise you keep: only the methods of a class should change its private data.

      Why This Matters

      When every change goes through one method, there is exactly one place to check the rules and one place to fix a bug. Salesforce service classes follow this pattern: they keep their working data private and expose a small set of public methods that do the job safely.

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In