当我们有访问器和mutator时,为什么要声明私有字段? [英] Why do we declare private fields when we have accessors and mutators?

查看:154
本文介绍了当我们有访问器和mutator时,为什么要声明私有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我用Java创建一个类,我总是被告知惯例是使一个类的所有字段都是私有的。如果我需要访问或更改它们,我可以创建一个访问器和mutator方法。我确实理解私有变量的重要性,因为它们有助于降低复杂性并允许封装。

If I create a class in Java, I've always been taught that the convention is to make all fields of a class private. If I need to access or change them, I can create an accessor and mutator method. I do understand the importance of private variables, as they help reduce complexity and allow for encapsulation.

我不明白的是,如果我创建一个公共访问者和mutator方法,那不是变量public?为什么在任何人都可以访问私有变量的情况下仍然使用私有变量?

What I don't understand is that if I create a public accesor and mutator method, isn't the variable public at that point? Why is it still convention to use private variables in situations where anyone can access them?

我还应该注意,我理解这些方法的重要性,但我想知道为什么我们懒得让变量私有即使我们通过这些方法给任何人访问它?

I should also note that I understand the important of these methods, but I would like to know why we bother to make the variable private even though we are giving anyone access to it through those methods?

推荐答案

是的,你是对的,它确实有效地使变量公开。但是有一个重要的区别,就是它让你能够在以后更改内容:你可以根据需要删除setter,或者将其设置为private,而不会影响使用getter从字段读取的代码。

Yes, you're right, it does effectively make the variable public. But there's one important difference, which is that it gives you the ability to change things later on: you can remove the setter if you want, or make it private, without affecting code that reads from the field using the getter.

如果您刚刚将变量设为公开,那么在不破坏字段读取的情况下,您将无法停止对该字段的写入。

If you'd just made the variable public, you wouldn't be able to stop writes to the field without also breaking reads from the field.

它还有其他优点。例如,如果您想稍后进行访问,可以进行 synchronized 访问,而不会破坏客户端代码。简而言之,它允许稍后进行大量修改,否则不会在使用该类的代码中造成大量破坏。

It has other advantages. You can make the access synchronized if you want to later on, without breaking client code, for instance. In short, it allows lots of modifications later on that wouldn't otherwise be possible without causing lots of breakages in code that uses the class.

并且您可以添加额外的逻辑每当有人写入字段时记录,或者阻止某些线程写入,或者等等......您可以将字段类型从 HashMap 更改为 TreeMap 如果你的getter将它抽象出去并且只返回一个 Map ......等等。

And you can add extra logic that logs whenever someone writes to the field, or prevents certain threads from writing, or whatever... you can change the type of a field from a HashMap to a TreeMap if your getter abstracts it away and just returns a Map... etc.

这篇关于当我们有访问器和mutator时,为什么要声明私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆