Programming lesson
Java Classes and Objects: Build a Smart Home Thermostat (Lab 5 Guide)
Learn Java classes, objects, and methods by designing a Smart Thermostat class. This tutorial covers constructors, getters/setters, toString(), and method types with real-world analogies from smart home tech and AI trends.
Introduction: Why Classes and Objects Matter in Java
In Java, everything revolves around classes and objects. Whether you're building a mobile app, a game, or a smart home system, understanding how to define classes and create objects is the foundation of object-oriented programming (OOP). This tutorial will guide you through creating a SmartThermostat class—a perfect real-world object that's trending with the rise of AI-powered home automation. By the end, you'll know how to implement instance variables, constructors, getters/setters, and multiple method types, just like your ICS 141 Lab 5 assignment requires.
Think of a class as a blueprint for a smart thermostat. The blueprint defines what properties (like current temperature, mode, and schedule) and behaviors (like adjusting temperature or switching modes) the thermostat will have. An object is an actual thermostat you can interact with in your home. Methods are the actions you can perform on that thermostat, such as turning it on or reading the temperature.
Part 1: Describing a Class – The SmartThermostat Blueprint
Your assignment asks you to pick a real-world object (not a car, animal, or book). Let's choose a SmartThermostat—a device that's become a staple in modern smart homes, especially with the integration of AI assistants like Alexa and Google Home. This object has clear attributes and behaviors that map well to Java classes.
Step 1: Create the Class
Create a new Java class named SmartThermostat. This class will represent the blueprint for any smart thermostat object.
public class SmartThermostat {
// instance variables will go here
}Step 2: Add Instance Variables
Instance variables represent the state of an object. For a SmartThermostat, we need three attributes:
- currentTemperature (double) – the current room temperature in Celsius.
- mode (String) – the operating mode, e.g., "cool", "heat", or "auto".
- scheduleEnabled (boolean) – whether the thermostat follows a daily schedule.
public class SmartThermostat {
private double currentTemperature;
private String mode;
private boolean scheduleEnabled;
}Notice we used private access modifier to encapsulate the data. This is good practice because it prevents direct access from outside the class, enforcing control through getters and setters.
Step 3: Add a Parameterized Constructor
A constructor initializes the object when it's created. Our constructor takes three parameters to set the initial values of the instance variables.
public SmartThermostat(double currentTemperature, String mode, boolean scheduleEnabled) {
this.currentTemperature = currentTemperature;
this.mode = mode;
this.scheduleEnabled = scheduleEnabled;
}Using this keyword distinguishes the instance variables from the parameters (which have the same names).
Step 4: Add Getters and Setters
Getters and setters allow controlled access to the private instance variables. Each variable gets a getter (to read the value) and a setter (to update the value).
public double getCurrentTemperature() {
return currentTemperature;
}
public void setCurrentTemperature(double currentTemperature) {
this.currentTemperature = currentTemperature;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public boolean isScheduleEnabled() {
return scheduleEnabled;
}
public void setScheduleEnabled(boolean scheduleEnabled) {
this.scheduleEnabled = scheduleEnabled;
}Notice the getter for a boolean variable is named isScheduleEnabled instead of getScheduleEnabled. This is a Java naming convention.
Step 5: Add a toString() Method
The toString() method returns a string representation of the object. It's automatically called when you print the object. This method helps with debugging and logging.
@Override
public String toString() {
return "SmartThermostat{" +
"currentTemperature=" + currentTemperature +
", mode='" + mode + '\'' +
", scheduleEnabled=" + scheduleEnabled +
'}';
}Using @Override annotation tells the compiler we are overriding the default toString() from the Object class.
Part 2: Programmer-Designed Methods – Adding Behavior
Your assignment requires four more methods: one void, one int, one String, and one static method. These methods give the SmartThermostat useful behaviors.
Method 1: void – adjustTemperature(double delta)
This method changes the current temperature by a given delta (positive to increase, negative to decrease). It returns nothing (void).
public void adjustTemperature(double delta) {
this.currentTemperature += delta;
// Ensure temperature stays within reasonable bounds
if (this.currentTemperature < 10.0) {
this.currentTemperature = 10.0;
} else if (this.currentTemperature > 35.0) {
this.currentTemperature = 35.0;
}
}This method is useful when you want to programmatically adjust the temperature, such as when a user says "Make it a bit cooler" to a voice assistant.
Method 2: int – getTemperatureInFahrenheit()
This method converts the current temperature (stored in Celsius) to Fahrenheit and returns the integer part. This is an int method.
public int getTemperatureInFahrenheit() {
double fahrenheit = (currentTemperature * 9/5) + 32;
return (int) fahrenheit; // cast to int
}Converting to Fahrenheit is common in countries like the United States. This method provides a quick integer value for display on a thermostat screen.
Method 3: String – getStatusReport()
This method returns a human-readable string describing the current state of the thermostat. It's a String method.
public String getStatusReport() {
String scheduleStatus = scheduleEnabled ? "schedule is active" : "schedule is off";
return "Current temp: " + currentTemperature + "°C, Mode: " + mode + ", " + scheduleStatus;
}This could be used to send a notification to the homeowner's phone or to display on a web dashboard.
Method 4: static – celsiusToFahrenheit(double celsius)
Static methods belong to the class, not to any specific object. They can be called without creating an object. This method converts a Celsius temperature to Fahrenheit and returns the double value.
public static double celsiusToFahrenheit(double celsius) {
return (celsius * 9/5) + 32;
}You can call this method as SmartThermostat.celsiusToFahrenheit(25.0) without needing a SmartThermostat object. Static methods are useful for utility functions that don't depend on instance state.
Part 3: Creating Objects – The ThingDriver Class
Your assignment asks you to create a driver class named after your object + "Driver". For our SmartThermostat, it's SmartThermostatDriver. This class contains the main method where we instantiate objects and test our code.
public class SmartThermostatDriver {
public static void main(String[] args) {
// Instantiate two SmartThermostat objects
SmartThermostat thermostat1 = new SmartThermostat(22.5, "cool", true);
SmartThermostat thermostat2 = new SmartThermostat(19.0, "heat", false);
// Print details of both objects
System.out.println("Thermostat 1: " + thermostat1);
System.out.println("Thermostat 2: " + thermostat2);
// Test additional methods
thermostat1.adjustTemperature(-2.0);
System.out.println("After adjusting: " + thermostat1.getCurrentTemperature() + "°C");
int fahrenheit = thermostat2.getTemperatureInFahrenheit();
System.out.println("Thermostat 2 in Fahrenheit: " + fahrenheit + "°F");
String report = thermostat1.getStatusReport();
System.out.println(report);
// Test static method
double converted = SmartThermostat.celsiusToFahrenheit(30.0);
System.out.println("30°C in Fahrenheit: " + converted + "°F");
}
}When you run this, you'll see the details of both thermostats printed using the toString() method, along with the results of the other method calls.
Part 4: Answering Conceptual Questions via Comments
Your assignment requires you to answer six questions using comments in your code. Here are the answers you can include:
/*
* 1. Similarities between Class, Object, and Method:
* - All are fundamental building blocks of OOP in Java.
* - Classes define methods, and objects are instances of classes.
* - Methods define behaviors that objects can perform.
*
* 2. Differences:
* - A class is a blueprint; an object is an instance of that blueprint.
* - A method is a block of code that performs a task; a class can contain many methods.
* - Classes are compile-time concepts; objects exist at runtime.
*
* 3. Importance of UML:
* - UML (Unified Modeling Language) provides a standard way to visualize the design of a system.
* - It helps in planning, communicating, and documenting class structures, relationships, and behaviors.
*
* 4. What happens when we add static to a method?
* - The method belongs to the class rather than any instance.
* - It can be called using the class name without creating an object.
* - Static methods cannot access instance variables directly.
*
* 5. Can we instantiate an object if the class doesn't have a constructor?
* - Yes, Java provides a default no-argument constructor if no constructor is defined.
* - Adding a constructor allows you to initialize instance variables with specific values at creation time.
*
* 6. How is a constructor different from a class?
* - A constructor is a special method that has the same name as the class and no return type.
* - It is used to initialize objects; the class defines the structure and behavior.
* - A class can have multiple constructors (overloading); a constructor is not a class.
*/Include these comments in your SmartThermostatDriver class (or in the SmartThermostat class) to fulfill the requirement.
Exporting and Submitting Your Code
Finally, your assignment asks you to export your code as a zip file. In Eclipse, right-click on the src folder, select Export, then General > Archive File. Choose the files to include, name the zip file as YourNameLab5.zip (e.g., DillonLab5.zip), and upload it to the D2L drop box.
Conclusion
In this tutorial, you learned how to design a Java class with instance variables, a parameterized constructor, getters/setters, and multiple method types using a SmartThermostat as your real-world object. This example connects to the growing trend of AI-powered smart homes, making the learning experience relevant and engaging. By following these steps, you'll be able to complete your ICS 141 Lab 5 assignment with confidence. Remember to test your code thoroughly and include the required comments. Happy coding!