foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Java
  • Learn getter and setter implementation
  • Understand naming conventions
  • Master validation in setters

Getters and Setters in Java

Getters and setters are how you let outside code read and change your private fields. They're the gatekeepers of encapsulation.

What are Getters and Setters?

Getters (Accessors)

Getters return the value of a private field. They give read access to encapsulated data.

public class Person {
    private String name;
    private int age;
    
    // Getter for name
    public String getName() {
        return name;
    }
    
    // Getter for age
    public int getAge() {
        return age;
    }
}

Setters (Mutators)

Setters are methods that modify the value of a private field. They provide write access to encapsulated data.

public class Person {
    private String name;
    private int age;
    
    // Setter for name
    public void setName(String name) {
        this.name = name;
    }
    
    // Setter for age with validation
    public void setAge(int age) {
        if (age >= 0 && age <= 150) {
            this.age = age;
        } else {
            throw new IllegalArgumentException("Invalid age: " + age);
        }
    }
}

Naming Conventions

Java follows specific naming conventions for getters and setters:

For Primitive Types and Objects:

  • Getter: get<FieldName>()
  • Setter: set<FieldName>(fieldType value)
private String firstName;
private int age;
private boolean isStudent;

public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }

public int getAge() { return age; }
public void setAge(int age) { this.age = age; }

public boolean isStudent() { return isStudent; }  // Note: 'is' instead of 'get'
public void setStudent(boolean student) { isStudent = student; }

For Boolean Fields:

  • Getter: is<FieldName>() (preferred) or get<FieldName>()
  • Setter: set<FieldName>(boolean value)

Advanced Getter and Setter Patterns

Computed Properties

Getters can compute and return derived values:

public class Rectangle {
    private double width;
    private double height;
    
    public double getArea() {
        return width * height;  // Computed property
    }
    
    public double getPerimeter() {
        return 2 * (width + height);  // Computed property
    }
}

Validation in Setters

Setters should validate input data:

public class Email {
    private String address;
    
    public void setAddress(String address) {
        if (address == null || address.trim().isEmpty()) {
            throw new IllegalArgumentException("Email address cannot be null or empty");
        }
        if (!address.contains("@")) {
            throw new IllegalArgumentException("Invalid email format");
        }
        this.address = address.toLowerCase().trim();
    }
}

Defensive Copying

For mutable objects, return copies to prevent external modification:

public class Person {
    private List<String> hobbies;
    
    public List<String> getHobbies() {
        return new ArrayList<>(hobbies);  // Return a copy
    }
    
    public void setHobbies(List<String> hobbies) {
        this.hobbies = new ArrayList<>(hobbies);  // Store a copy
    }
}

IDE Generation

Most IDEs can automatically generate getters and setters:

Eclipse/IntelliJ IDEA:

  1. Right-click in the class
  2. Select "Generate" or "Source Action"
  3. Choose "Getters and Setters"
  4. Select the fields you want to generate for

Generated Code Example:

// Original field
private String name;

// Generated getter and setter
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

Common Mistakes

1. Direct Field Access

// Wrong - breaks encapsulation
person.name = "John";

// Correct - uses encapsulation
person.setName("John");

2. Missing Validation

// Wrong - no validation
public void setAge(int age) {
    this.age = age;  // Allows negative ages
}

// Correct - with validation
public void setAge(int age) {
    if (age >= 0) {
        this.age = age;
    }
}

3. Incorrect Boolean Getter Names

private boolean active;

// Wrong
public boolean getActive() { return active; }

// Correct
public boolean isActive() { return active; }

When to Use Getters and Setters

Always Use for:

  • Fields that need validation
  • Fields that might change implementation
  • Fields accessed by multiple classes
  • Fields that need to trigger side effects

Sometimes Skip for:

  • Simple data containers (DTOs) - consider public final fields
  • Internal helper classes
  • Performance-critical code (rare)

Getters and setters give you controlled access to private fields. They let you validate input, change implementation later without breaking existing code, and keep your data safe. Follow naming conventions (get/set/is), validate in setters, and you'll write code that's both secure and flexible.

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service