wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes what is the use of getters and setters? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "what is the use of getters and setters?" Watch "what is the use of getters and setters?" New topic
Author

what is the use of getters and setters?

Karthikeyan Ramaswamy
Ranch Hand

Joined: Apr 30, 2008
Posts: 41
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 ?

Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

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>
santosh joshi
Greenhorn

Joined: Aug 20, 2007
Posts: 21
For providing data Encapsulation.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: what is the use of getters and setters?
 
Similar Threads
Can we send multiple textfield of same type in struts
Overloading Constructors
jsp:useBean conceptual problem
getter and setter methods.