何时使用 java 中的 get/set 方法

发布于 2024-10-02 02:31:54 字数 600 浏览 5 评论 0原文

我想知道何时在我的类中使用 get 和 set 方法(getName,setName ) 以及何时使用简单的 classVariable.name = "" 而不是 а = classVariable.getName()

这是使用 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;
    }
}

谢谢

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

Here is example of class using set and get methods

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

少女净妖师 2024-10-09 02:31:54

使用 Getters/Setter 与使用字段

根据经验:

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

Using Getters / Setters vs using Fields

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.

甜妞爱困 2024-10-09 02:31:54

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

  • 字段访问无法被代理
  • 您可能想要一些事件通知
  • 您可能想要防止竞争条件
  • 表达式语言支持 setter 和 getter
  • 理论上这会破坏封装。 (如果我们很迂腐,那么所有字段的 setter 和 getter 也会破坏封装)
  • 可能想要在 setter 或 getter 内部执行一些额外的逻辑,但这很少是可取的,因为消费者希望这样做约定 - 即作为一个简单的 getter/setter。
  • 您可以仅指定一个 setter 或仅指定一个 getter,从而实现只读或只写访问。

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

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 may want 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.

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.

鱼忆七猫命九 2024-10-09 02:31:54

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

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

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

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

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.

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.

花开柳相依 2024-10-09 02:31:54

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

优点之一是您可以获得的不仅仅是简单的分配和返回。例子:

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;
}

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

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;
}
猫卆 2024-10-09 02:31:54

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

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

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

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

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

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

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.

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 += 5 which is easier to read than obj.setVar(obj.getVar() + 5).

烂人 2024-10-09 02:31:54

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

如果您的意思是,调用您自己的 get 和 set 方法与直接访问类中的变量,我仍然说调用您自己的访问方法。这样,您作为 get/set 的一部分实现的任何转换、编辑或规则都会由您自己的内部调用以及外部调用者自动调用。

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

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

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.

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.

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.

倾其所爱 2024-10-09 02:31:54

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

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.

久伴你 2024-10-09 02:31:54

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

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


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

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


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

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.

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.


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.


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

北凤男飞 2024-10-09 02:31:54

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文