Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Setter and Getter [closed]

It is always recommended to use getter/setter for accessing private variables. Why would it not be a better idea to declare them as public and access them. Anyway we are accessing it using getter and setter?

like image 892
nikhil Avatar asked Aug 26 '11 16:08

nikhil


2 Answers

Encapsulation.

Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

See also:

  • What Is an Object
like image 54
mre Avatar answered Sep 21 '22 17:09

mre


@mre answer is excellent and your question is fundamental. To summarize : you put the fields of an object private to gain control over the way it will be used by other objects. Your object uses setter to:

  • restrict and validate data passed to the setter
  • hide its inner data structure (other object are interested by a service not how the service is built, this can also include optimisation)
  • preserve its integrity in every state (changing other fields if required)

it will use getter to

  • format data in output as desired by the client
  • control a sequence of services (for instance it will provide data if and only if a connection has been established)

welcome in the wonderfull world of OO programming and the magics of structured programming.

Stéphane

like image 31
Snicolas Avatar answered Sep 20 '22 17:09

Snicolas