Implementing Getters and Setters in Java
Course: Core Java Training
Topic: Implementing Getters and Setters
Course URL: Core Java Training Course
Demo URL: Register for Course Demo
Official Website: JustAcademy
1. Introduction to Getters and Setters
Getters and setters are methods in Java used to retrieve and modify the values of class fields. They are commonly used to implement encapsulation, an important principle of object-oriented programming. By declaring fields as private and providing controlled access through methods, developers can protect an object's internal data.
A getter retrieves a field's value, while a setter assigns a new value to the field. Setters can also validate incoming values before updating the object's state.
Example
class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In this example, the name field is private. The getName() method retrieves its value, and the setName() method updates it.
2. Learning Objectives
- Understand getters, setters, and their purpose.
- Learn how to implement accessor and mutator methods.
- Understand private fields and encapsulation.
- Use the
this keyword correctly.
- Validate values before modifying fields.
- Implement read-only properties where required.
- Apply getters and setters in practical Java programs.
- Identify common implementation mistakes.
3. Understanding Encapsulation
Encapsulation means combining data and related methods within a class while controlling access to the object's internal state. In Java, encapsulation is commonly implemented by declaring fields as private and exposing only the methods required by other classes.
Example Without Encapsulation
class Employee {
public String name;
public double salary;
}
public class Main {
public static void main(String[] args) {
Employee employee = new Employee();
employee.name = "Rahul";
employee.salary = -5000;
System.out.println(employee.name);
System.out.println(employee.salary);
}
}
Problem: Since the fields are public, other classes can assign invalid values without going through any validation logic.
Example With Encapsulation
class Employee {
private String name;
private double salary;
public String getName() {
return name;
}
public void setName(String name) {
if (name != null && !name.trim().isEmpty()) {
this.name = name;
} else {
throw new IllegalArgumentException(
"Name cannot be empty."
);
}
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
if (salary >= 0) {
this.salary = salary;
} else {
throw new IllegalArgumentException(
"Salary cannot be negative."
);
}
}
}
This implementation protects the fields and validates values before assigning them.
4. What Is a Getter Method?
A getter is an accessor method that returns the current value of a field. It normally has a public access modifier and a return type matching the field's data type.
Syntax
public dataType getFieldName() {
return fieldName;
}
Example
class Product {
private String productName;
public String getProductName() {
return productName;
}
}
public class Main {
public static void main(String[] args) {
Product product = new Product();
System.out.println(product.getProductName());
}
}
Output:
null
The output is null because the instance field is a reference type that has not been assigned a value. A getter returns the current value; it does not initialize the field automatically.
Important Characteristics of Getters
- They provide access to a field's value without exposing the field directly.
- They usually do not modify the object's state.
- They return a value using the
return statement.
- They can perform calculations or return derived information when appropriate.
5. What Is a Setter Method?
A setter is a mutator method that changes the value of a field. It typically accepts a parameter and assigns it to the corresponding instance variable.
Syntax
public void setFieldName(dataType value) {
this.fieldName = value;
}
Example
class Product {
private String productName;
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductName() {
return productName;
}
}
public class Main {
public static void main(String[] args) {
Product product = new Product();
product.setProductName("Laptop");
System.out.println(product.getProductName());
}
}
Output:
Laptop
Important Characteristics of Setters
- They accept values through method parameters.
- They can validate input before changing a field.
- Conventional setters usually return
void.
- They provide controlled modification of private fields.
6. Understanding the this Keyword
The this keyword refers to the current object. It is particularly useful when a method parameter has the same name as an instance field.
class Student {
private String name;
public void setName(String name) {
this.name = name;
}
}
In this example:
this.name refers to the instance field.
name refers to the parameter passed to the method.
Without this, the statement name = name; would assign the parameter to itself and would not update the instance field.
7. Implementing Getters and Setters Step by Step
- Create a class: Define a class representing an entity such as a student or employee.
- Declare private fields: Add the data that the class needs to store.
- Create getter methods: Return the required field values.
- Create setter methods: Accept new values and assign them to the fields.
- Add validation: Check whether incoming values satisfy the class's rules.
- Create an object: Instantiate the class in the main method.
- Call setters: Assign valid values through public methods.
- Call getters: Retrieve and display the stored information.
8. Complete Java Program Using Getters and Setters
class Student {
private String name;
private int age;
private double marks;
public String getName() {
return name;
}
public void setName(String name) {
if (name != null && !name.trim().isEmpty()) {
this.name = name;
} else {
throw new IllegalArgumentException(
"Name cannot be empty."
);
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age >= 1 && age <= 120) {
this.age = age;
} else {
throw new IllegalArgumentException(
"Age must be between 1 and 120."
);
}
}
public double getMarks() {
return marks;
}
public void setMarks(double marks) {
if (marks >= 0 && marks <= 100) {
this.marks = marks;
} else {
throw new IllegalArgumentException(
"Marks must be between 0 and 100."
);
}
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.setName("Aarav");
student.setAge(20);
student.setMarks(88.5);
System.out.println("Student Name: " + student.getName());
System.out.println("Student Age: " + student.getAge());
System.out.println("Student Marks: " + student.getMarks());
}
}
Output:
Student Name: Aarav
Student Age: 20
Student Marks: 88.5
Program Explanation
- The
Student class contains three private fields.
- Each field has a getter that returns its current value.
- The setters validate the supplied values before assigning them.
- The main method creates a
Student object.
- Valid information is assigned through setter methods.
- Getter methods retrieve the stored values for display.
- If invalid data is supplied, an exception is thrown rather than silently accepting it.
9. Getters and Setters for Different Data Types
Integer Field
class Account {
private int accountNumber;
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
}
Boolean Field
class User {
private boolean active;
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
For boolean properties, the isActive() convention is common. The appropriate naming convention can depend on the project's standards and framework requirements.
Double Field With Validation
class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
if (balance >= 0) {
this.balance = balance;
} else {
throw new IllegalArgumentException(
"Balance cannot be negative."
);
}
}
}
For financial applications, BigDecimal is generally preferable to double for representing monetary values because floating-point arithmetic can introduce precision errors.
10. Read-Only and Write-Only Properties
Read-Only Property
A read-only property exposes a getter without a public setter. This allows callers to retrieve a value without changing it through the public API.
class Employee {
private final int employeeId;
public Employee(int employeeId) {
this.employeeId = employeeId;
}
public int getEmployeeId() {
return employeeId;
}
}
The employee ID is assigned through the constructor and cannot be reassigned because it is declared final.
Write-Only Property
A write-only property provides a setter without a corresponding getter. This can be useful in limited cases where callers need to submit a value but should not retrieve it through that class's public API.
class Configuration {
private String setting;
public void setSetting(String setting) {
this.setting = setting;
}
}
Write-only access does not automatically make sensitive data secure. Passwords and credentials require appropriate secure storage and handling.
11. Difference Between Getters and Setters
| Feature |
Getter |
Setter |
| Purpose |
Retrieves a value |
Updates a value |
| Common naming |
getName() |
setName(value) |
| Parameters |
Usually none |
Usually one or more |
| Return type |
Usually the field's data type |
Usually void |
| State modification |
Usually does not modify state |
Usually modifies state |
| Validation |
May calculate or prepare returned data |
Can validate incoming values |
12. Getters and Setters vs. Public Fields
| Feature |
Public Fields |
Getters and Setters |
| Access |
Direct access |
Access through methods |
| Validation |
No validation on direct assignment |
Validation can be included |
| Encapsulation |
Limited control |
Supports controlled access |
| Read-only design |
Requires other mechanisms |
Getter can be provided without a setter |
| Maintenance |
Callers depend on the field |
Internal implementation can change behind a stable API |
Getters and setters are not automatically better in every situation. Create them when controlled access, validation, compatibility, or a clear public API is needed. Avoid exposing unnecessary methods that allow callers to modify internal state.
13. Common Mistakes and Their Solutions
Mistake 1: Forgetting the Return Statement
// Incorrect
public String getName() {
name;
}
// Correct
public String getName() {
return name;
}
A non-void getter must return a value compatible with its declared return type.
Mistake 2: Incorrect Assignment
// Incorrect
public void setAge(int age) {
age = age;
}
// Correct
public void setAge(int age) {
this.age = age;
}
The correct statement assigns the parameter to the instance field.
Mistake 3: Missing Validation
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException(
"Age cannot be negative."
);
}
this.age = age;
}
Validation helps protect the class from invalid data. The exact rules should reflect the application's requirements.
Mistake 4: Incorrect Naming Conventions
// Conventional getter
public String getName() {
return name;
}
// Conventional setter
public void setName(String name) {
this.name = name;
}
Consistent naming improves readability and compatibility with tools that inspect JavaBean-style properties.
Mistake 5: Exposing Mutable Internal Data
import java.util.ArrayList;
import java.util.List;
class Team {
private final List<String> members = new ArrayList<>();
public List<String> getMembers() {
return new ArrayList<>(members);
}
public void addMember(String member) {
members.add(member);
}
}
Returning a defensive copy helps prevent callers from modifying the internal list directly. Alternative approaches include immutable collections and methods that expose only necessary operations.
14. Best Practices for Getters and Setters
- Declare fields private when external direct access is not appropriate.
- Use clear, consistent method names.
- Use the
this keyword when parameter names overlap with field names.
- Validate input before changing the object's state.
- Choose a consistent way to report invalid input, such as exceptions.
- Avoid unnecessary setters for immutable or read-only fields.
- Do not expose passwords or other sensitive information through getters.
- Use defensive copying for mutable objects when needed.
- Consider constructors for required fields and initial validation.
- Write tests for normal values, invalid values, and boundary conditions.
- Do not assume getters and setters automatically make a class thread-safe.
15. Real-World Example: Product Management
class Product {
private String productName;
private double price;
private int quantity;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
if (productName == null || productName.trim().isEmpty()) {
throw new IllegalArgumentException(
"Product name cannot be empty."
);
}
this.productName = productName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if (price < 0) {
throw new IllegalArgumentException(
"Price cannot be negative."
);
}
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
if (quantity < 0) {
throw new IllegalArgumentException(
"Quantity cannot be negative."
);
}
this.quantity = quantity;
}
}
public class Main {
public static void main(String[] args) {
Product product = new Product();
product.setProductName("Laptop");
product.setPrice(55000);
product.setQuantity(10);
System.out.println("Product: " + product.getProductName());
System.out.println("Price: " + product.getPrice());
System.out.println("Quantity: " + product.getQuantity());
}
}
Output:
Product: Laptop
Price: 55000.0
Quantity: 10
This example demonstrates controlled access to product information. Invalid product names, negative prices, and negative quantities are rejected before the fields are updated.
16. Getters and Setters in JavaBeans
JavaBeans are reusable Java components that commonly follow conventions for constructors, properties, and methods. A traditional JavaBean often provides a public no-argument constructor and getter/setter methods for its properties.
public class Customer {
private String customerName;
public Customer() {
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
Frameworks and libraries may use these conventions to discover and access properties through reflection. Not every Java class needs to follow the complete JavaBeans pattern.
17. Modern Java Alternatives
IDE-Generated Getters and Setters
Java development environments can generate getters and setters automatically. Generated methods save time, but developers should review whether the class needs validation, read-only fields, or other access restrictions.
Java Records
Java records provide a concise way to define data-oriented classes. They automatically provide component accessors using the component names rather than conventional get-prefixed methods.
public record Student(String name, int age) {
}
Usage:
Student student = new Student("Aarav", 20);
System.out.println(student.name());
System.out.println(student.age());
Output:
Aarav
20
Records are suitable for many data-carrier use cases, but they do not replace every mutable class. Their component fields are final, although objects referenced by components may still be mutable.
18. Testing Getters and Setters
Testing verifies that getters return expected values and setters update fields according to the class's rules.
Example
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("Neha");
if ("Neha".equals(person.getName())) {
System.out.println("Test passed.");
} else {
System.out.println("Test failed.");
}
}
}
Output:
Test passed.
Testing Checklist
- Verify that a getter returns the assigned value.
- Verify that a setter accepts valid values.
- Verify that invalid values are rejected.
- Check whether failed updates preserve the previous valid value.
- Test null values and boundary conditions.
- Verify that returned mutable objects cannot unexpectedly change internal state.
19. Practice Exercises
Exercise 1: Employee Class
Create an Employee class with private fields for employee ID, name, and salary.
- Implement getters and setters.
- Require the employee ID to be positive.
- Reject null or empty names.
- Prevent negative salaries.
- Display the employee information through getters.
Exercise 2: Bank Account Class
Create a BankAccount class containing an account holder name and balance.
- Use a getter to retrieve the account holder name.
- Validate the initial balance.
- Implement deposit and withdrawal methods.
- Prevent invalid amounts and withdrawals exceeding the available balance.
Exercise 3: Book Class
Create a Book class with private fields for title, author, and publication year. Implement getters and setters and validate the supplied values.
Exercise 4: Read-Only Registration Number
Create a class with a final registration number assigned through a constructor. Provide a getter but no setter.
20. Mini Project: Student Information Management
Build a simple Java application to store and display student information using encapsulation and getters and setters.
Project Requirements
- Create a
Student class with ID, name, age, and marks fields.
- Declare the fields private.
- Implement getters for required properties.
- Implement setters with suitable validation.
- Create multiple student objects in the main class.
- Display student information through getters.
- Test both valid and invalid input.
Expected Learning Outcomes
After completing the project, learners should be able to implement encapsulation, protect object state, validate input, and organize Java classes using clear public interfaces.
21. Interview Questions and Answers
Q1. What is a getter in Java?
A getter is an accessor method that retrieves the value of a field.
Q2. What is a setter in Java?
A setter is a mutator method that updates a field, usually after receiving a value through a parameter.
Q3. Why are fields declared private?
Private fields prevent direct access from outside the class and help control how the object's state is accessed and modified.
Q4. How do getters and setters support encapsulation?
They allow a class to expose selected operations on its private fields without making the fields directly accessible.
Q5. Can a class have a getter without a setter?
Yes. This provides read-only access through the class's public interface.
Q6. Can a class have a setter without a getter?
Yes. This provides a way to submit a value without providing a corresponding retrieval method.
Q7. Why is this used in a setter?
The this keyword refers to the current object and distinguishes an instance field from a parameter with the same name.
Q8. Are getters and setters required for every field?
No. Methods should be provided according to the class's requirements. Unnecessary setters may expose more control over an object than intended.
Q9. Can a setter validate data?
Yes. A setter can check incoming values and reject invalid input before modifying a field.
Q10. What is the difference between a getter and a setter?
A getter retrieves a value, while a setter updates a value.
Q11. What are JavaBean naming conventions?
JavaBean-style properties commonly use methods such as getName(), setName(String name), and isActive() for boolean properties.
Q12. What is an alternative to traditional getters and setters for data classes?
Java records provide component accessors such as student.name() and are useful for concise data-oriented classes.
22. Quick Revision Checklist
- Understand encapsulation and private fields.
- Use getters to retrieve values.
- Use setters to update values when modification is required.
- Follow Java naming conventions.
- Use the
this keyword correctly.
- Validate values before assigning them.
- Understand read-only and write-only properties.
- Protect mutable internal objects when necessary.
- Test valid, invalid, and boundary values.
- Expose only the methods that callers actually need.
23. Conclusion
Getters and setters are fundamental Java techniques for managing access to class fields. They support encapsulation, enable input validation, and provide a clear interface between objects. Well-designed classes use getters and setters where they add value instead of automatically generating them for every field.
By practicing with student, employee, product, and bank account examples, learners can develop a strong understanding of data hiding and object-oriented programming in Java.
Learn Core Java with JustAcademy
Explore the Core Java Training Course to learn Java fundamentals, classes and objects, encapsulation, inheritance, polymorphism, exception handling, collections, and other essential programming concepts.
Register for a Course Demo to explore the learning experience and course details.
Visit the JustAcademy official website to discover more courses and learning resources.