Getters and setters are used to implement two of the fundamental aspects of Object Oriented Programming which are:
- Abstraction
- Encapsulation
Suppose we have an Employee class:
package com.highmark.productConfig.types;public class Employee { private String firstName; private String middleName; private String lastName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFullName(){ return this.getFirstName() + this.getMiddleName() + this.getLastName(); } }
Here the implementation details of Full Name is hidden from the user and is not accessible directly to the user, unlike a public attribute.