0
0
JavaHow-ToBeginner · 3 min read

How to Create Getter and Setter in Java: Simple Guide

In Java, create a getter method to read a private field and a setter method to update it. These methods allow controlled access to private variables by using public methods named typically as getFieldName() and setFieldName().
📐

Syntax

A getter method returns the value of a private field, and a setter method sets or updates the value of that field.

They are usually public methods with no parameters for getters and one parameter for setters.

java
private DataType fieldName;

public DataType getFieldName() {
    return fieldName;
}

public void setFieldName(DataType fieldName) {
    this.fieldName = fieldName;
}
💻

Example

This example shows a Person class with a private name field and its getter and setter methods. It demonstrates how to read and update the name safely.

java
public class Person {
    private String name;

    // Getter method
    public String getName() {
        return name;
    }

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

    public static void main(String[] args) {
        Person person = new Person();
        person.setName("Alice");
        System.out.println("Name: " + person.getName());
    }
}
Output
Name: Alice
⚠️

Common Pitfalls

  • Forgetting to make fields private defeats the purpose of encapsulation.
  • Not using this keyword in setters can cause confusion when parameter names match field names.
  • Creating setters without validation can allow invalid data.
  • Omitting getters or setters when needed limits access or modification.
java
public class Example {
    private int age;

    // Wrong setter: missing 'this' keyword
    public void setAge(int age) {
        age = age; // This assigns parameter to itself, not the field
    }

    // Correct setter
    public void setAgeCorrect(int age) {
        this.age = age;
    }
}
📊

Quick Reference

Use getters and setters to protect your data and control how fields are accessed or changed.

  • Getter: public DataType getFieldName() returns the field value.
  • Setter: public void setFieldName(DataType value) updates the field.
  • Keep fields private for encapsulation.
  • Use this keyword in setters to avoid confusion.

Key Takeaways

Getters and setters provide controlled access to private fields in Java classes.
Always declare fields as private and use public getter and setter methods.
Use the this keyword in setters to clearly assign values to fields.
Validate data inside setters to keep object state consistent.
Omitting getters or setters limits how fields can be accessed or changed.