Java 当我能够使用 setter 方法更改属性值时,封装有什么用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16418571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the use of encapsulation when I'm able to change the property values with setter methods?
提问by PSR
I try to understand a lot of times but I failed to understand this.
我试图理解很多次,但我没能理解这一点。
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class.
封装是将类中的字段设为私有并通过公共方法提供对字段的访问的技术。如果一个字段被声明为私有,类外的任何人都无法访问它,从而隐藏了类内的字段。
How can we change the values of fields through setter methods? How do we prevent accessing the fields directly? What is the real use of encapsulation?
我们如何通过 setter 方法更改字段的值?我们如何防止直接访问字段?封装的真正用途是什么?
采纳答案by npinti
Assume you have an age
property.
假设你有一个age
财产。
The user can enter a value of -10
, which although is a valid number, is an invalid age. A setter method could have logic which would allow you to catch such things.
用户可以输入 的值-10
,该值虽然是有效数字,但却是无效年龄。setter 方法可以具有允许您捕获此类内容的逻辑。
Another scenario, would be to have the age
field, but hide it. You could also have a Date of Birth field, and in it's setter you would have something like so:
另一种情况是拥有该age
字段,但将其隐藏。你也可以有一个出生日期字段,在它的二传手中你会有这样的东西:
...
private int age
private Date dob
...
public void setDateOfBirth(Date dob)
{
this.dob = dob;
age = ... //some logic to calculate the age from the Date of Birth.
}
回答by Thilo
Any how i am able to change the values of fields through setter methods.
我如何能够通过 setter 方法更改字段的值。
Only if the setter method lets you do that.
仅当 setter 方法允许您这样做时。
How we are preventing the accessing fields?
我们如何防止访问字段?
The setter and getter get to control if and how you can access the fields.
setter 和 getter 可以控制您是否以及如何访问这些字段。
A setter may check if the value is valid. It may ask a SecurityManager if you should be allowed to do this. It may convert between data types. And so on.
setter 可以检查该值是否有效。它可能会询问 SecurityManager 是否应该允许您这样做。它可以在数据类型之间进行转换。等等。
回答by Eugene
The real use of encapsulation is also in the fact that you can do additional checks/processing on the way the values are set.
封装的真正用途还在于您可以对设置值的方式进行额外的检查/处理。
回答by Suresh Atta
If you have class all of its properties are private-meaning that they cannot be accessed from outside the class- and the only way to interact with class properties is through its public methods.
如果你有类,它的所有属性都是私有的——这意味着它们不能从类外部访问——并且与类属性交互的唯一方法是通过它的公共方法。
You are changing tha values by giving the public access to those methods(setters).
您通过公开访问这些方法(setter)来更改 tha 值。
using encapsulation the fields of a class can be made read-only
or write-only.
使用封装可以制作类的字段read-only
或write-only.
回答by mikey
You're not exactly preventing access to the fields -- you're controlling how others can access certain fields. For example you can add validation to your setter method, or you can also update some other dependent field when the setter method of a field is called.
您并没有完全阻止对字段的访问——您正在控制其他人如何访问某些字段。例如,您可以向 setter 方法添加验证,或者您还可以在调用字段的 setter 方法时更新某些其他依赖字段。
You can prevent write or read access to the field (e.g. by only providing a getter or setter respectively) -- but encapsulation with properties allows you to do more than just that.
您可以阻止对该字段的写入或读取访问(例如,仅分别提供一个 getter 或 setter)——但使用属性封装允许您做的远不止这些。
回答by aran
It's aim is nothing but protecting anything which is prone to change. You have plenty of examples on the web, so I give you some of the advantages of it:
它的目的只是保护任何容易发生变化的东西。你在网上有很多例子,所以我给你一些它的优点:
- Encapsulated Code is more flexibleand easy to change with new requirements
- Allows you to control who can access what. (!!!)
- Helps to write
immutable class
in Java - It allows you to change one partof code without affecting other part of code.
- 封装的代码更灵活,更容易随着新的需求而改变
- 允许您控制谁可以访问什么。(!!!)
- 有助于
immutable class
用 Java编写 - 它允许您更改代码的一部分而不影响其他部分的代码。
回答by user2245180
Instead of letting everyone access the variables directly:
而不是让每个人直接访问变量:
public Object object;
Is better to use SET and GET methods, or for example just the GET method (Sometimes you dont want nobody to set other value to that variable).
最好使用 SET 和 GET 方法,或者例如仅使用 GET 方法(有时您不希望没有人为该变量设置其他值)。
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
回答by Evgeniy Dorofeev
Accessing fields thru methods make difference because it makes it OOP. Eg you can extend you class and change the behaviour which you cannot do with direct access. If you have getters / setters you can make a proxy of your class and do some AOP or a make a 1.4 dynamic proxy. You can make a mock from your class and make unit testing...
通过方法访问字段会有所不同,因为它使它成为 OOP。例如,您可以扩展类并更改直接访问无法实现的行为。如果你有 getter/setter,你可以为你的类做一个代理并做一些 AOP 或做一个 1.4 动态代理。您可以从您的班级中进行模拟并进行单元测试...
回答by MMeersseman
Lets suppose you make a custom Date class with the following setters / getters:
假设您使用以下 setter/getter 创建一个自定义 Date 类:
getDay()
getMonth()
getYear()
setDay()
setMonth()
setYear()
Internally you could store the date using:
在内部,您可以使用以下方法存储日期:
private int day;
private int month;
private int year;
Or you could store the date using a java.lang.Date-object:
或者您可以使用 java.lang.Date 对象存储日期:
private Date date;
Encapsulation doesn't expose how your class is working internally. It gives you more freedom to change how your class works. It gives you the option to control the access to your class. You can check if what the user enters is valid (you don't want the user to enter a day with a value of 32).
封装不会公开您的类在内部是如何工作的。它使您可以更自由地更改课程的工作方式。它使您可以选择控制对类的访问。您可以检查用户输入的内容是否有效(您不希望用户输入值为 32 的一天)。
回答by Sello
If you have private fields they can't be accessed outside the class, that means basically those fields don't exist to the outside world and yes you can change their value through setter methods but using setter methods you have more flexibility/control to say who gets to change the fields and to what value can they be changed to...basically with encapsulation you get to put restrictions on how and who changes your fields. For example you have: private double salary, you setter method could restrict that only hr staff can change the salary field it could be written as:
如果您有私有字段,则无法在类外部访问它们,这意味着基本上这些字段对外部世界不存在,是的,您可以通过 setter 方法更改它们的值,但是使用 setter 方法,您可以更灵活/控制地说谁可以更改字段以及它们可以更改为什么值......基本上通过封装,您可以对如何以及谁更改您的字段进行限制。例如,您有:私人双薪,您的 setter 方法可以限制只有 hr 员工可以更改薪水字段,它可以写为:
void setSalary(Person p,double newSalary)
{
//only HR objects have access to change salary field.
If(p instanceof HR && newSalary>=0)
//change salary.
else
S.o.p("access denied");
}
Imagine if salary was public and could be access directly any can change it however and whenever they want, this basically the significance of encapsulation
想象一下,如果工资是公开的并且可以直接访问,任何人都可以随时更改它,这基本上就是封装的意义