Define a constructor that take no parameters

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 Java, followed by a detailed 300-word explanation:

✅ Java Code:

public class Heater {
    private int temperature;

    // Constructor with no parameters
    public Heater() {
        temperature = 15; // Set default temperature
    }

    // Mutator method to increase temperature by 5
    public void warmer() {
        temperature += 5;
    }

    // Mutator method to decrease temperature by 5
    public void cooler() {
        temperature -= 5;
    }

    // Accessor method to get current temperature
    public int getTemperature() {
        return temperature;
    }
}

📘 Explanation (300+ words):

In object-oriented programming (OOP), classes represent blueprints for objects, encapsulating data (fields) and behavior (methods). The above code defines a Java class named Heater, which demonstrates encapsulation, constructor use, method creation, and field access principles.

  1. Field Declaration:
    The Heater class contains a private integer field named temperature. This variable stores the state of the heater’s current temperature. It is marked private to prevent direct modification from outside the class, ensuring data protection and control through methods.
  2. Constructor:
    The constructor public Heater() is a no-argument constructor, meaning it does not take any parameters when creating a Heater object. Inside the constructor, temperature is initialized to 15. This ensures that every new Heater object starts with a consistent initial state.
  3. Mutators (Setters):
    The warmer() method is a mutator that increases the temperature by 5 units using temperature += 5. Similarly, the cooler() method decreases the temperature by 5 using temperature -= 5. These methods allow controlled modification of the internal state, instead of direct access.
  4. Accessor (Getter):
    The method getTemperature() is an accessor that returns the current value of the temperature field. It provides read-only access to the internal state, allowing other classes to retrieve the temperature without modifying it.

This design promotes data encapsulation, a core principle of OOP. By using private fields and public methods, we ensure that the internal state of the object can only be changed in predictable and controlled ways. This pattern improves maintainability, scalability, and security of the code.

Scroll to Top