get 和 set 方法有什么意义

Nat*_*tan 0 java oop encapsulation class

在我的 CS 课程中,我只是在学习课程和 OOP。

因此,当您创建一个类时,您会初始化一定数量的私有变量。

我知道您将它们设为私有,因为如果它们是公开的,它们将很容易更改并可能导致很多错误。

所以我们使用 get 和 set 方法来改变变量。但这再次使变量很容易改变,对吗?那么首先将它们设为私有有什么意义呢?

nem*_*035 6

使用 getter 和 setter(称为encapsulationdata-hiding)的一些好处:

1. 类的字段可以设置为只读(只提供getter)或只写(只提供setter)。这使类可以完全控制谁可以访问/修改其字段。

例子:

class EncapsulationExample {
    private int readOnly = -1;  // this value can only be read, not altered
    private int writeOnly = 0;    // this value can only be changed, not viewed
    public int getReadOnly() {
        return readOnly;
    }
    public int setWriteOnly(int w) {
        writeOnly = w;
    }
}
Run Code Online (Sandbox Code Playgroud)

2. 类的用户不需要知道类实际上是如何存储数据的。这意味着数据与用户分开并独立存在,从而使代码更容易修改和维护。这允许维护人员进行频繁的更改,例如错误修复、设计和性能增强,同时不会影响用户。

此外,封装的资源对于每个用户都可以统一访问,并且具有独立于用户的相同行为,因为该行为是在类中内部定义的。

示例(获取值):

class EncapsulationExample {
    private int value;
    public int getValue() {     
        return value; // return the value
    }
}
Run Code Online (Sandbox Code Playgroud)

现在如果我想返回两倍的值呢?我可以更改我的 getter 并且所有使用我的示例的代码都不需要更改,并且将获得两倍的值:

class EncapsulationExample {
    private int value;
    public int getValue() {
        return value*2; // return twice the value
    }
}
Run Code Online (Sandbox Code Playgroud)

3. 使代码更清晰、更易读、更容易理解。

下面是一个例子:

无封装:

class Box {
    int widthS; // width of the side
    int widthT; // width of the top
    // other stuff
}

// ...
Box b = new Box();
int w1 = b.widthS;  // Hm... what is widthS again? 
int w2 = b.widthT;  // Don't mistake the names. I should make sure I use the proper variable here!
Run Code Online (Sandbox Code Playgroud)

带封装:

class Box {
    private int widthS; // width of the side
    private int widthT; // width of the top
    public int getSideWidth() {
        return widthS;
    }
    public int getTopWIdth() {
        return widthT;
    }
    // other stuff
}

// ...
Box b = new Box();
int w1 = b.getSideWidth(); // Ok, this one gives me the width of the side
int w2 = b.getTopWidth(); // and this one gives me the width of the top. No confusion, whew!
Run Code Online (Sandbox Code Playgroud)

看看在第二个示例中,您对获得的信息有多少控制权,以及这点有多清晰。请注意,这个例子是微不足道的,在现实生活中,您将处理由许多不同组件访问的大量资源的类。因此,封装资源使我们更清楚我们正在访问哪些资源以及以何种方式(获取或设置)。

这是good SO thread关于这个主题。

这里是good read关于数据封装。