DEV Community

silambarasan rajendran
silambarasan rajendran

Posted on

3

day-22: Getter Methods in Java: Best Practices for Clean and Secure Code

Getter Method in Java (Simple Explanation)
A getter method is a public method that provides controlled read access to a private field in a class.

Why Use a Getter?
Encapsulation → Keeps fields (private) hidden but allows safe access.
Security → Prevents direct modification of sensitive data.
Flexibility → You can later add logic (e.g., formatting, validation) without breaking existing code.

Example: Getter for goldRate

public class SriKumaranTangaMaligai {
    private int goldRate = 5000;  // Private field (hidden)

    // Getter method (read-only access)
    public int getGoldRate() {
        return goldRate;  // Returns the value of goldRate
    }
}
Enter fullscreen mode Exit fullscreen mode

How to Use the Getter?

public class User {
    public static void main(String[] args) {
        SriKumaranTangaMaligai shop = new SriKumaranTangaMaligai();

        // Access goldRate via getter (not directly)
        System.out.println("Gold Rate: ₹" + shop.getGoldRate());  
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Points
✔ Naming Convention: Getters start with get + FieldName (e.g., getGoldRate).
✔ Return Type: Matches the field’s type (int, String, etc.).
✔ No Parameters: Getters only return values (no arguments).

Getter vs. Direct Public Access
Approach Pros Cons
Getter (getGoldRate()) Safe, controlled, future-proof Slightly more code
Public Field (goldRate) Shorter, faster No validation, breaks encapsulation

When to Avoid Getters?
In high-performance code where direct access is critical.
For simple data containers (use Java record instead)

Heroku

Tired of jumping between terminals, dashboards, and code?

Check out this demo showcasing how tools like Cursor can connect to Heroku through the MCP, letting you trigger actions like deployments, scaling, or provisioning—all without leaving your editor.

Learn More

Top comments (0)

Tiger Data image

🐯 🚀 Timescale is now TigerData: Building the Modern PostgreSQL for the Analytical and Agentic Era

We’ve quietly evolved from a time-series database into the modern PostgreSQL for today’s and tomorrow’s computing, built for performance, scale, and the agentic future.

So we’re changing our name: from Timescale to TigerData. Not to change who we are, but to reflect who we’ve become. TigerData is bold, fast, and built to power the next era of software.

Read more

👋 Kindness is contagious

Explore this insightful piece, celebrated by the caring DEV Community. Programmers from all walks of life are invited to contribute and expand our shared wisdom.

A simple "thank you" can make someone’s day—leave your kudos in the comments below!

On DEV, spreading knowledge paves the way and fortifies our camaraderie. Found this helpful? A brief note of appreciation to the author truly matters.

Let’s Go!