Computed Properties: Getters Without Backing Fields
What You'll Learn
You'll learn how to create getter methods that calculate and return values on-the-fly instead of storing them in instance variables.
The Core Idea
Not every getter needs a matching field. Sometimes, a property's value can be computed from other existing fields whenever it's requested. This technique saves memory, ensures the computed value is always current, and often makes your class design cleaner.
Think of it like asking someone their age versus their birth year. You might store their birth year as a field, but their age can be calculated whenever needed—no need to store both!
How It Works
A computed property getter looks like any other getter, but instead of simply returning a field's value, it performs a calculation:
public class Rectangle {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
// Regular getters with backing fields
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
// Computed property: no 'area' field exists!
public double getArea() {
return width * height;
}
// Another computed property
public double getPerimeter() {
return 2 * (width + height);
}
}
Notice there's no area or perimeter field. These values are calculated fresh every time the getter is called, using the current width and height.
When to Use Computed Properties
- The value can be derived from other fields
- The value changes whenever the underlying fields change
- Storing the value separately would waste memory or risk becoming stale
- The calculation is simple and fast
Key Takeaway: Computed properties use getters to calculate values from existing fields on-demand, eliminating redundant storage and ensuring values stay synchronized with their source data.