Menu
Coddy logo textTech

Getter and Setter Methods

Part of the Object Oriented Programming section of Coddy's Java journey. Lesson 11 of 87.

Getters and setters are methods that provide controlled access to private fields. A getter retrieves a field's value, while a setter modifies it.

The naming convention follows a standard pattern: prefix get or set followed by the field name with its first letter capitalized.

public class Product {
    private String name;
    private double price;
    
    // Getter for name
    public String getName() {
        return name;
    }
    
    // Setter for name
    public void setName(String name) {
        this.name = name;
    }
    
    // Getter for price
    public double getPrice() {
        return price;
    }
    
    // Setter with validation
    public void setPrice(double price) {
        if (price >= 0) {
            this.price = price;
        }
    }
}

The real power of setters is the ability to add validation logic. In the example above, setPrice only accepts non-negative values, protecting the object from invalid data.

For boolean fields, getters typically use the prefix is instead of get:

private boolean active;

public boolean isActive() {
    return active;
}

You can also create read-only fields by providing only a getter, or write-only fields by providing only a setter. This gives you fine-grained control over how external code interacts with your object's data.

challenge icon

Challenge

Easy

Let's build a Temperature converter that demonstrates the power of getters and setters with validation logic.

You'll create two files to organize your code:

  • Temperature.java: Define a Temperature class that stores a temperature value in Celsius. The class should have:
    • A private celsius field (double)
    • A private valid field (boolean) that tracks whether the temperature is physically possible
    • A getter getCelsius() that returns the celsius value
    • A setter setCelsius() that only accepts values at or above absolute zero (-273.15). If the value is valid, set valid to true; otherwise, don't change celsius and set valid to false
    • A getter isValid() for the boolean field (remember: boolean getters use is prefix)
    • A getter getFahrenheit() that converts and returns the temperature in Fahrenheit using the formula: (celsius * 9/5) + 32
  • Main.java: Create a Temperature object, read a celsius value as input, use the setter to set it, then print whether the temperature is valid and its Fahrenheit equivalent. Format your output as two lines:
    • Valid: true or Valid: false
    • Fahrenheit: X.X (showing one decimal place)

You will receive one input: a double value representing a temperature in Celsius.

For formatting the Fahrenheit output to one decimal place, you can use String.format("%.1f", value).

Try it yourself

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double celsiusInput = scanner.nextDouble();
        
        // TODO: Create a Temperature object
        
        // TODO: Use the setter to set the celsius value
        
        // TODO: Print whether the temperature is valid (format: "Valid: true" or "Valid: false")
        
        // TODO: Print the Fahrenheit equivalent (format: "Fahrenheit: X.X")
        // Hint: Use String.format("%.1f", value) for one decimal place
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online Java compiler