java - 类的公共(public)成员如何在 Java 中造成严重破坏?

标签 java class public

类的公共(public)成员如何在 java 中造成严重破坏?有人可以举例说明吗?我试图创造这样的情况,但没有成功。我只是发现它们等同于“ protected ”访问修饰符。

最佳答案

它允许无效值,破坏封装。

public class Clock {
    public int hours;
    public int minutes;
}

然后,在不相关的代码中...

Clock clock = new Clock();
clock.hours = 42;
clock.minutes = 99;

使用 setter 和 getter 方法将它们设为私有(private)允许封装以强制执行正确的值。

public class Clock {
    private int hours;
    private int minutes;
    public void setHours(int hours) {
        if (hours < 0 || hours > 23) throw new IllegalArgumentException("bad range");
        this.hours = hours;
    }
    // Likewise for "setMinutes" method.
}

这是一个 tutorial page on encapsulation in Java关于封装的好处。引用:

  • The fields of a class can be made read-only or write-only.

  • A class can have total control over what is stored in its fields.

  • The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.

关于java - 类的公共(public)成员如何在 Java 中造成严重破坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18410497/

相关文章:

java - 在jsp中连接url

java - 当我尝试从 Java 桥接设备监听模块时,为什么我的 Android 会立即响应 native 应用程序崩溃

php - 限制什么可以创建 PHP 类

java - 在 Ubuntu 中的 Java 中使用同一包中的类

c++ - 将对象转换为不同的类

java - 公共(public)类需要公共(public)成员(访问成员时)?

java - 如何部署一个简单的Drools应用程序?

java - 使用 java 从 Payment Gateway 重定向时,我丢失了 session 数据

struct - 如何在强制使用 "new"构造函数的同时使结构的所有字段公开可读

.net - 将内部类公开为公共(public)属性