类的公共(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/