可以在java中理解setter和getter

And*_*omi 2 java getter setter class

我是java的新手,但我喜欢这种语言,我希望自己变得尽可能好,但我对"课堂"的事情仍然有些困难.我理解一个类是什么,什么是对象,但我仍然无法理解好的getter和setter

我知道上课了

  • 实例变量
  • 构造函数
  • 方法
  • 塞特犬和吸气剂?

我无法理解为什么我需要它们,如果我应该在构造函数中编写它们.

还要指出我已经阅读了几篇互联网文章但是

  1. 那些是"技术性的"
  2. 他们只是编写一个没有实例变量的代码,构造函数让我无法理解

即使您是像我这样的初学者,也非常感谢您的帮助^^

编辑:

例如,我应该如何在这里使用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");
    } 
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 6

您需要它们以允许您的类的用户获取和设置参数.这允许您的类跟踪何时设置参数,例如检查约束,强制一致性,更新其他值,使缓存无效.封装还允许您在保持API兼容的同时修改版本之间的类的内部表示.


JB *_*zet 6

你问了一个简单的例子,所以我会给一个.假设你正在设计一个圆圈类.圆的特征在于其直径:

public class Circle {
    private double diameter;

    public Circle(double diameter) {
        this.diameter = diameter;
    }
}
Run Code Online (Sandbox Code Playgroud)

调用者可能想知道圆的直径,因此您添加一个getter:

public class Circle {
    private double diameter;

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

    public double getDiameter() {
        return this.diameter;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能还想获得圆的区域,因此您为该区域添加了一个getter:

public double getArea() {
    return Math.PI * (this.diameter / 2) * (this.diameter / 2);
}
Run Code Online (Sandbox Code Playgroud)

然后你意识到使用半径而不是直径对于圆的内部方法更容易.但是你希望保持你班级的所有用户不变,以避免破坏现有的许多代码.因此,您无需更改界面即可更改类的内部:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,您想要更改圆的直径,因此您添加了一个setter:

public void setDiameter(double diameter) {
    this.radius = diameter / 2;
}
Run Code Online (Sandbox Code Playgroud)

但是等一下,一个负直径的圆圈是没有意义的,所以你让方法更安全:

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

如果你在施工时预先计算了该区域,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;
    }
}
Run Code Online (Sandbox Code Playgroud)

吸气剂和制定者只是方法.但是它们遵循一种命名约定,使您的代码易于掌握,并且可以被许多依赖于这些约定的框架使用.