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
EasyLet'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
celsiusfield (double) - A private
validfield (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, setvalidto true; otherwise, don't change celsius and setvalidto false - A getter
isValid()for the boolean field (remember: boolean getters useisprefix) - A getter
getFahrenheit()that converts and returns the temperature in Fahrenheit using the formula:(celsius * 9/5) + 32
- A private
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: trueorValid: falseFahrenheit: 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).
Cheat sheet
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;
}
}
}Setters can include validation logic to protect objects from invalid data. In the example above, setPrice only accepts non-negative values.
For boolean fields, getters use the prefix is instead of get:
private boolean active;
public boolean isActive() {
return active;
}You can create read-only fields by providing only a getter, or write-only fields by providing only a setter.
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
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System