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.
- Field Declaration:
TheHeaterclass contains a private integer field namedtemperature. This variable stores the state of the heater’s current temperature. It is markedprivateto prevent direct modification from outside the class, ensuring data protection and control through methods. - Constructor:
The constructorpublic Heater()is a no-argument constructor, meaning it does not take any parameters when creating aHeaterobject. Inside the constructor,temperatureis initialized to15. This ensures that every newHeaterobject starts with a consistent initial state. - Mutators (Setters):
Thewarmer()method is a mutator that increases the temperature by 5 units usingtemperature += 5. Similarly, thecooler()method decreases the temperature by 5 usingtemperature -= 5. These methods allow controlled modification of the internal state, instead of direct access. - Accessor (Getter):
The methodgetTemperature()is an accessor that returns the current value of thetemperaturefield. 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.