• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Junilu Lacar
  • Liutauras Vilda
Sheriffs:
  • Paul Clapham
  • Jeanne Boyarsky
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
Bartenders:
  • Jesse Duncan
  • Frits Walraven
  • Mikalai Zaikin

what is the use of getters and setters?

 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

i have a doubt, In below class

class employeeVO {

private String name;

public void setName(String name)
{
this.name=name;
}

public String getName()
{
return name;
}

}

We are using POJO class like this, but why we are keeping variable scope as private,
In setter & getter we are not doing anything, then we can keep variable as public & directly access like
below right.

employee empObj = new employee();
empObj.name = "Test"
String name = empObj.name

what is the intention behind to keep variable scope as private ?

 
Ranch Hand
Posts: 5575
Eclipse IDE Windows XP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Karthikeyan Ramaswamy wrote:
what is the intention behind to keep variable scope as private ?


because allowing a user to change the instance field of a class is not a good Idea.

reason: working with method is easier than fields.
1. suppose you want to apply a common logic[synchronize etc...] when ever user set some value into the field.
2. importantly, instance variable dont have polymorphic behavior.
<edit>
3. setObject and getObject are more expressive than object.instanceVar = and = object.instanceVar
</edit>
 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For providing data Encapsulation.
 
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic