问题
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?
回答1:
@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
回答2:
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
回答3:
All of the answers above are excellent, but let me add one more point.
You do not want all of your private variables to have public getters and setters.
Your getters and setters refer to externally visible state. In some cases, what looks like a single object as published in your public methods corresponds to more than one internal private variable for the implementation. In a complex object, many of your private variables won't map to something externally visible. Some people automatically write setters and getters for them anyway, but this is a bad idea because it exposes your implementation details.
回答4:
I was always told that one of the main reasons is to try and plan for future changes. It may start out as just
public int getInt() { return _someInt;}
but may end up as
public int getInt() {
// do some processing
return _someInt;
}
and that would save you from having to make massive amounts of changes to where you accessed the public property instead of using the getter/setter.
回答5:
Usually a setter allows you to keep restrictions on the type of values being assigned to a private member. So perhaps negative values are not allowed, etc.
A getter, since you've imposed access to the member by making it private for the reasons above, allows consumers access to the value of that member.
回答6:
All of the other answers are great and very true. Here is yet another reason why I have found it helpful.
Using the getters and setters on an object is the largest part of following the JavaBean convention. Although following it to the letter is often difficult and overkill, at the very least many third party frameworks/libraries/expression languages depend on the getters and setters convention for accessing the fields of an object. If you follow it up front, then you can already use the objects with these other very useful libraries without having to update your objects.
Examples I have used include:
- Jsp
- Freemarker
- jXls
- Spring (although Spring is so robust you don't have to follow the convention)
- SpEL (really any expression language)
回答7:
I use regularly getter and setter but apparently we are not doing it right. For example: (obtained from http://java.dzone.com/articles/java-properties-without )
with getter & setter (way long)
public class Teacher {
@Id @Column(length=5) @Required
private String id;
@Column(length=40) @Required
private String name;
@OneToMany(mappedBy="teacher")
private Collection pupils;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection getPupils() {
return pupils;
}
public void setPupils(Collection pupils) {
this.pupils = pupils;
}
}
with public: (only 13 lines, counting blank lines).
@Entity
public class Teacher {
@Id @Column(length=5) @Required
public String id;
@Column(length=40) @Required
public String name;
@OneToMany(mappedBy="teacher")
public Collection pupils;
}
calling with getter & setter (not a bit clear, however C# makes it cleaner).
teacher.setName("M. Carmen");
String result = teacher.getName();
calling public (direct and clean).
teacher.name = "M. Carmen";
String result = teacher.name;
One is verbose and it add more code (and code cost in working hour and in process time), while the other is direct.
In some cases, it is mandatory to use setter and getter but if not, then i think that it is a bit overkill to use it as default.
来源:https://stackoverflow.com/questions/7207994/java-setter-and-getter