简体   繁体   English

可以在java中理解setter和getter

[英]Can understand setters and getters in java

I'm new to java, but I like the language and I want to become as good as possible but I still have some difficulties with the "class" thing. 我是java的新手,但我喜欢这种语言,我希望自己变得尽可能好,但我对“课堂”的事情仍然有些困难。 I understand what a class is and what objects are but still I cant understand well getters and setters 我理解一个类是什么,什么是对象,但我仍然无法理解好的getter和setter

I know a class has 我知道上课了

  • Instance variables 实例变量
  • Constructors 构造函数
  • Methods 方法
  • Setters and getters ? 塞特犬和吸气剂?

I can't understand well why do I need them and if I should write those inside a constructor. 我无法理解为什么我需要它们,如果我应该在构造函数中编写它们。

Also like to point out that I've read several internet articles but 还要指出我已经阅读了几篇互联网文章但是

  1. those were to much "technical" 那些是“技术性的”
  2. they just write a code without instance variables, constructors so I can't understand very well 他们只是编写一个没有实例变量的代码,构造函数让我无法理解

Your help is very appreciated even if you are a beginner like me ^^ 即使您是像我这样的初学者,也非常感谢您的帮助^^

Edit: 编辑:

For example how i should use the setters and getters here? 例如,我应该如何在这里使用setter和getters?

class Demo {

    int a=4;
    Int b;

    public Demo () {
        System.println("a is <than b")
    };

    public int Demo (int b) { 
        if (a<b)
            System.out.println("a is < than b");
        else
            System.out.println("b is < than a");
    } 
}

You need them to allow users of your class to get and set parameters. 您需要它们以允许您的类的用户获取和设置参数。 This allows your class to keep track of when parameters are set and eg check constraints, enforce consistency, update other values, invalidate caches. 这允许您的类跟踪何时设置参数,例如检查约束,强制一致性,更新其他值,使缓存无效。 The encapsulation also allows you to modify the internal representation of the class between versions while keeping the API compatible. 封装还允许您在保持API兼容的同时修改版本之间的类的内部表示。

You asked for a simple example, so I'll give one. 你问了一个简单的例子,所以我会给一个。 Suppose you're designing a circle class. 假设你正在设计一个圆圈类。 A circle can be characterized by its diameter: 圆的特征在于其直径:

public class Circle {
    private double diameter;

    public Circle(double diameter) {
        this.diameter = diameter;
    }
}

A caller might want to know the diameter of the circle, so you add a getter: 调用者可能想知道圆的直径,因此您添加一个getter:

public class Circle {
    private double diameter;

    public Circle(double diameter) {
        this.diameter = diameter;
    }

    public double getDiameter() {
        return this.diameter;
    }
}

You might also want to get the area of the circle, so you add a getter for the area: 您可能还想获得圆的区域,因此您为该区域添加了一个getter:

public double getArea() {
    return Math.PI * (this.diameter / 2) * (this.diameter / 2);
}

And then you realize that using the radius rather than the diameter is easier for the internal methods of the circle. 然后你意识到使用半径而不是直径对于圆的内部方法更容易。 But you want to keep all the users of your class as is, to avoid breaking a lot of existing code. 但是你希望保持你班级的所有用户不变,以避免破坏现有的许多代码。 So you change the internals of the class without changing the interface: 因此,您无需更改界面即可更改类的内部:

public class Circle {
    private double radius;

    public Circle(double diameter) {
        this.radius = diameter / 2;
    }

    public double getArea() {
        return Math. PI * radius * radius;
    }

    public double getDiameter() {
        return this.radius * 2;
    }
}

And finally, you would like to change the diameter of the circle, so you add a setter: 最后,您想要更改圆的直径,因此您添加了一个setter:

public void setDiameter(double diameter) {
    this.radius = diameter / 2;
}

But wait, a circle with a negative diameter makes no sense, so you make the method safer: 但是等一下,直径为负的圆圈没有意义,所以你让方法更安全:

public void setDiameter(double diameter) {
    if (diameter <= 0) {
        throw new IllegalArgumentException("diameter must be > 0");
    }
    this.radius = diameter / 2;
}

Had you precomputed the area at construction time, the setDiameter would have had to change the value of the area as well: 如果你在施工时预先计算了该区域,setDiameter也必须改变该区域的值:

public class Circle {
    private double radius;
    private double area;

    public Circle(double diameter) {
        this.radius = diameter / 2;
        this.area = Math. PI * radius * radius;
    }

    public double getArea() {
        return area;
    }

    public double getDiameter() {
        return this.radius / 2;
    }

    public void setDiameter(double diameter) {
        this.radius = diameter / 2;
        // the area must also be changed, else the invariants are broken.
        this.area = Math. PI * radius * radius;
    }
}

Getters and setters are just methods. 吸气剂和制定者只是方法。 But they follow a naming conventions that makes your code easy to grasp, and usable by a number of frameworks which rely on these conventions. 但是它们遵循一种命名约定,使您的代码易于掌握,并且可以被许多依赖于这些约定的框架使用。

A getter or setter is just a function that returns a class property, or sets a class property. getter或setter只是一个返回类属性或设置类属性的函数。 The reason you use them is because typically class properties are defined as private , which means you can only reference them directly within class methods. 您使用它们的原因是因为通常将类属性定义为private ,这意味着您只能在类方法中直接引用它们。

A getter is a public method (meaning it can be called from outside of the class itself) that returns a private value. getter是一个public方法(意思是它可以从类本身外部调用),它返回一个私有值。 This allows the property to remain private but still be accessible outside of the class. 这允许该属性保持私有,但仍可在课堂外访问。

A setter is a public method that sets a private value. setter是一个设置私有值的public方法。 As you may have guessed, this allows the property to remain private but still be set outside of the class. 正如您可能已经猜到的那样,这允许该属性保持私有但仍然被设置在该类之外。

Setters and getters are just methods that are used to access fields associated with a class: Setter和getter只是用于访问与类关联的字段的方法:

class Demo {

    int a;

    public Demo () { a=4; }

    public int getDemo () { return a; }

    public void setDemo (int a) { this.a=a; }

}

The getters and setters are a way of accessing Java Bean properties associated with a class. getter和setter是一种访问与类关联的Java Bean属性的方法。 It's just a standard means of being able to access the public fields that the class is interested in sharing. 它只是能够访问该类有兴趣共享的公共字段的标准方法。 They are defined by the Java Bean specification. 它们由Java Bean规范定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM