0
0
Javaprogramming~5 mins

Getter and setter methods in Java

Choose your learning style9 modes available
Introduction

Getter and setter methods help you safely get and change the values inside an object. They keep data private and controlled.

When you want to protect data inside an object from being changed directly.
When you want to check or change data before saving it.
When you want to hide how data is stored inside an object.
When you want to make your code easier to maintain and understand.
When you want to follow good programming rules about data privacy.
Syntax
Java
public class ClassName {
    private DataType variableName;

    public DataType getVariableName() {
        return variableName;
    }

    public void setVariableName(DataType variableName) {
        this.variableName = variableName;
    }
}

Getters usually start with get and return the variable value.

Setters usually start with set and take a parameter to update the variable.

Examples
This example shows a simple getter and setter for a name variable.
Java
public class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
This setter checks that the balance is not negative before setting it.
Java
public class BankAccount {
    private double balance;

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        if (balance >= 0) {
            this.balance = balance;
        }
    }
}
Sample Program

This program creates a Car object, sets its color using the setter, and then prints the color using the getter.

Java
public class Car {
    private String color;

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.setColor("Red");
        System.out.println("Car color: " + myCar.getColor());
    }
}
OutputSuccess
Important Notes

Always keep variables private to protect data.

Use getters and setters to control how variables are accessed and changed.

You can add checks inside setters to prevent invalid data.

Summary

Getters and setters control access to private data inside objects.

Getters return the value, setters update the value.

They help keep your code safe and easy to manage.