make a class, Heater that contains a single integer field, temperature.

make a class, Heater that contains a single integer field, temperature. Define a constructor that take no parameters. The temperature field should be set to the value 15 in constructor. Define the mutators(setter) warmer and cooler method, whose effect is to increase or decrease the value of the temperature by 5 respectively. Define an accessor (getter) to return the value of temperature.

The Correct Answer and Explanation is:

Here is the correct implementation of the Heater class in Python:

class Heater:
    def __init__(self):
        self.temperature = 15  # Constructor initializes temperature to 15

    def warmer(self):
        self.temperature += 5  # Increases temperature by 5

    def cooler(self):
        self.temperature -= 5  # Decreases temperature by 5

    def get_temperature(self):
        return self.temperature  # Accessor to return current temperature

Explanation (300+ words):

In object-oriented programming, a class is a blueprint for creating objects that encapsulate data (fields) and behaviors (methods). The Heater class in this example demonstrates a simple structure containing one data field and a few methods to manipulate and access that data.

Field:

The class has one field called temperature, which stores the current temperature as an integer. This variable is defined within the constructor using the self keyword, which refers to the instance of the class.

Constructor:

The method __init__() is the constructor in Python. It is automatically called when a new object of the class is created. In this case, it takes no parameters other than self and sets the temperature to a default value of 15. This ensures that any Heater object begins at a consistent, expected state.

Mutator Methods:

Mutators, also called setters, are used to modify the value of private or internal fields. The class defines two mutator methods:

  • warmer(self) increases the temperature by 5 degrees. It uses the += operator to increment the value.
  • cooler(self) decreases the temperature by 5 degrees using the -= operator.

These methods allow controlled modification of the temperature field, maintaining encapsulation.

Accessor Method:

The get_temperature(self) method is an accessor or getter. It returns the current value of temperature. Accessors are important for retrieving the internal state of an object without directly exposing or allowing modification of the internal data from outside the class.

Usage:

heater = Heater()
heater.warmer()
print(heater.get_temperature())  # Outputs 20
heater.cooler()
print(heater.get_temperature())  # Outputs 15

This class follows basic principles of encapsulation, data hiding, and modular design, making it a good example of introductory object-oriented programming.

Scroll to Top