何时在 Java 中使用 get/set 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4156820/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:08:58  来源:igfitidea点击:

When to use get/set Methods in java

javagetter-setter

提问by Jovan

I want to know when to use get and set methods(getName,setName ) in my class and when simple classVariable.name = ""instead а = classVariable.getName()

我想知道什么时候用得到,并在我的课,当简单的设置方法(的getName,的setName)classVariable.name = ""代替а = classVariable.getName()

Here is example of class using set and get methods

这是使用 set 和 get 方法的类示例

public class ClassExampe {

    String name;
    String course;

    public String getName ( )
    {
        return name;
    }

    public void setName (String studentName)
    {
        name = studentName;           
    }

    public String getCourse ( )
    {
        return course;
    }

    public void setCourse (String studentCourse)
    {
        course = studentCourse;
    }
}

Thanks

谢谢

采纳答案by Sean Patrick Floyd

Using Getters / Setters vs using Fields

使用 Getter/Setter 与使用字段

As a rule of thumb:

根据经验:

use the variables directly from the same class (actually from the same .java file, so inner classes are ok too), use Getters / Setters from other classes.

直接使用来自同一个类的变量(实际上来自同一个 .java 文件,所以内部类也可以),使用来自其他类的 Getter/Setter。

回答by Piotr

Its a matter of taste, but generally speaking you always should use get/set methods for all properties that are public. But for things like Value Objects (VOs) that you probably are not going to be bothered with for some time you can use public variables without getting too much criticism I think.

这是一个品味问题,但一般来说,您应该始终对所有公共属性使用 get/set 方法。但是对于诸如值对象 (VO) 之类的东西,您可能在一段时间内不会被打扰,我认为您可以使用公共变量而不会受到太多批评。

回答by Alan Geleynse

In Java, using a getter and setter is usually considered best practice.

在 Java 中,使用 getter 和 setter 通常被认为是最佳实践。

This is because if you ever need to change your code to do something else when a property is accessed or modified, you can just change it in the existing getter or setter.

这是因为如果您在访问或修改属性时需要更改代码以执行其他操作,则只需在现有的 getter 或 setter 中更改它即可。

I tend to think it causes a bit of clutter for simple objects, but if you have ever had to refactor a public property to a getter and setter to add additional functionality you will see that it can be a pain.

我倾向于认为它会给简单的对象造成一些混乱,但是如果您曾经不得不将公共属性重构为 getter 和 setter 以添加附加功能,您会发现这可能会很痛苦。

回答by Bozho

The simple rule is: never use direct access (except, of course, when referring to them from inside the class).

简单的规则是:永远不要使用直接访问(当然,从类内部引用它们时除外)。

  • field access can't be proxied
  • you may want to have some event notification
  • you may want to guard against race conditions
  • expression languages support setters and getters
  • theoretically this breaks encapsulation. (If we are pedantic, setter and getter for all fields also breaks encapsulation though)
  • you maywant to perform some extra logic inside the setter or getter, but that is rarely advisable, since consumers expect this to follow the convention - i.e. being a simple getter/setter.
  • you can specify only a setter or only a getter, thus achieving read-only, or write-only access.
  • 无法代理现场访问
  • 你可能想要一些事件通知
  • 你可能想防止竞争条件
  • 表达式语言支持 setter 和 getter
  • 从理论上讲,这会破坏封装。(如果我们学究,所有字段的 setter 和 getter 也会破坏封装)
  • 可能希望在 setter 或 getter 中执行一些额外的逻辑,但这很少是可取的,因为消费者希望这遵循约定 - 即成为一个简单的 getter/setter。
  • 您可以只指定一个 setter 或只指定一个 getter,从而实现只读或只写访问。

Even if this does not happen that you need any of these, it is not unlikely. And if you start with field access, it will be harder to change.

即使这不会发生,您需要其中任何一个,这也不是不可能的。如果您从现场访问开始,将更难改变。

回答by FrustratedWithFormsDesigner

I suspect most will say to always use getters/setters to access private members. It's not necessary, but is considered a "best practice".

我怀疑大多数人会说总是使用 getter/setter 来访问私有成员。这不是必需的,但被认为是“最佳实践”。

One advantage is that you can have more than just simple assignment and returning. Example:

一个优点是您可以拥有的不仅仅是简单的分配和返回。例子:

public void setLevel(int lvl)
{
    if (lvl<0)
    {
        this.level=1;
    }
    else
        this.level = lvl;
}

public int getLevel()
{
    if (this.someIndicator==4)
        return this.level*7.1;
    else
        return level;
}

回答by Adrian Smith

Getters and Setters allow you to change the implementation later (e.g. do something more complex), allow you to implement validation rules (e.g. setNamethrows an exception if the name is not more than 5 characters, whatever.)

Getters 和 Setters 允许您稍后更改实现(例如,做一些更复杂的事情),允许您实现验证规则(例如setName,如果名称不超过 5 个字符,则抛出异常,无论如何。)

You could also choose to add a getter but not a setter so that the variable is like 'read-only'.

您还可以选择添加 getter 而不是 setter,以便变量类似于“只读”。

That's the theory, however in many cases (e.g. Hibernate using setters) you cannot throw exceptions in setters so you can't do any validation. Normally the value will just be assigned/returned. In some companies I've worked at, it's been mandatory to write getters and setters for all attributes.

这就是理论,但是在许多情况下(例如使用 setter 的 Hibernate)您不能在 setter 中抛出异常,因此您无法进行任何验证。通常,该值只会被分配/返回。在我工作过的一些公司中,必须为所有属性编写 getter 和 setter。

In that case, if you want to access an attribute from outside an object, and you want it to be readable/writable, I just use a public attribute. It's less code, and it means you can write things like obj.var += 5which is easier to read than obj.setVar(obj.getVar() + 5).

在这种情况下,如果您想从对象外部访问属性,并且希望它可读/可写,我只使用公共属性。它的代码更少,这意味着您可以编写obj.var += 5obj.setVar(obj.getVar() + 5).

回答by Joe

If you mean: when to use public accessor methods instead of making the internal, private variable public my answer is "always" unless there is a severe performance reason.

如果您的意思是:何时使用公共访问器方法而不是将内部私有变量设为公共我的答案是“总是”,除非有严重的性能原因。

If you mean, call your own get and set methods vs direct access to the vars w/in your class I still say call your own access methods. This way, any conversion, edits or rules you implement as part of get/set get invoked automatically by your own internal calls as well as external callers.

如果你的意思是,调用你自己的 get 和 set 方法与直接访问你的类中的 vars 我仍然说调用你自己的访问方法。这样,您在 get/set 中实现的任何转换、编辑或规则都会被您自己的内部调用和外部调用者自动调用。

In pure OO languages (for example, Smalltalk) there is no concept of public - all internal vars are private and so you must use accessors. In less pure OO languages, you can make things public - however exposing the internals of your data structures and implementation is an exceptionally bad idea for stability and maintenance in the long run. Look up "tight coupling" for more on this.

在纯 OO 语言(例如 Smalltalk)中,没有公共的概念——所有内部变量都是私有的,因此您必须使用访问器。在不太纯的面向对象语言中,您可以将事情公开——但是,从长远来看,公开数据结构和实现的内部结构对于稳定性和维护来说是一个非常糟糕的主意。查找“紧耦合”以了解更多信息。

Simply put, if you expose internal vars publicly, people can access them directly and if you ever change name or type everything down the line breaks. This is called side effects.

简而言之,如果您公开公开内部变量,人们可以直接访问它们,并且如果您更改名称或在换行符下键入所有内容。这称为副作用。

回答by haylem

In general, you'd want to use setters and getters to give the opportunity to developers reusing your code by modifying it or extending it to add layers of processing and control when accessing and modifying your internal data. This wouldn't be possible in Java when using direct accesses.

通常,您希望使用 setter 和 getter 为开发人员提供机会,通过修改或扩展代码来重用您的代码,以便在访问和修改内部数据时添加处理和控制层。使用直接访问时,这在 Java 中是不可能的。

Parenthesis: However, it's perfectly possible in other languages, for instance in Scala, when the line between properties and methods can become quite fine. And it's great, as then it doesn't become a coding-problem that gets in the way and it makes usage more transparent.

括号: 但是,在其他语言中完全有可能,例如在 Scala 中,属性和方法之间的界限可以变得非常好。这很棒,因为这样它就不会成为妨碍使用的编码问题,并且使使用更加透明。



You can also often consider that in your class you can feel free to access your internal (private or protected) members directly, as you're supposed to know what you're doing, and you don't need to incur the overhead of yet another method call.

您还可以经常考虑,在您的班级中,您可以随意直接访问您的内部(私有或受保护)成员,因为您应该知道自己在做什么,而且您不需要承担尚未另一个方法调用。

In practice, multiple people working on a class might not know what everyone's doing and those lines of integrity checking in your getters and setters might be useful in most cases, while the micro-optimization may not.

在实践中,在一个类上工作的多个人可能不知道每个人在做什么,并且在大多数情况下,你的 getter 和 setter 中的那些完整性检查线可能有用,而微优化可能没有。



Moreover, there's only one way for you to access a variable directly, whereas you can define as many accessors as you want.

此外,只有一种方法可以让您直接访问变量,而您可以根据需要定义任意数量的访问器。

回答by dimitrisli

Encapsulate the private fields of a class and expose them with getter/setter classes the way you want to.

封装类的私有字段,并按照您想要的方式使用 getter/setter 类公开它们。