Encapsulation: hiding state behind a contract

Encapsulation means controlling how internal state is accessed and changed. Without it, any code can put the system into an invalid state.

Implement a Thermostat class:

  • Constructor takes an initial temperature (Celsius)
  • setTemperature(temp) — sets the temperature, but only if it's between -10 and 40 (inclusive). If out of range, print Out of range and leave unchanged.
  • getTemperature() — returns the current temperature

Your program receives comma-separated operations:

  • start:<n> — create thermostat at n°C
  • set:<n> — call setTemperature
  • get — print the temperature
Input:  start:20,set:25,get,set:99,get
Output: 25
        Out of range
        25

Constraints

  • Valid range: -10 to 40 inclusive.
  • Print Out of range (exact) on rejected sets.
Ad SpaceGoogle AdSense active for guests & free-tier learners.