Quantcast
Channel: Why use getters and setters/accessors? - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by Pritam Banerjee for Why use getters and setters/accessors?

$
0
0

Getters and setters are used to implement two of the fundamental aspects of Object Oriented Programming which are:

  1. Abstraction
  2. 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.


Viewing all articles
Browse latest Browse all 38

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>