我浏览了几篇博客,从中得出以下几点。
Encapsulation Blog
不要将字段公开,因为任何其他类都可以直接修改变量。
使用getter和setter修改变量。
通过在getter和setter中包含验证,我们可以控制变量将不会被直接修改。
我在这里有点困惑。
考虑具有名称和地址作为其字段的Employee
。 Organization
和Organization2
类将为员工变量分配值并打印出来。
public class Employee {
public String name;
public String address;
public void printEmpDetails() {
System.out.println("Employee name :" + name + ", Employee address :"
+ address);
}
}
public class Organization {
public static void main(String[] args) {
System.out.println("Employee details of org");
Employee emp = new Employee(); //New Instance variable created
emp.name= "JOHN";
emp.address = "JOHN ADDRESS";
}
}
public class Organization2 {
public static void main(String[] args) {
System.out.println("Employee details of org2");
Employee emp = new Employee(); //New Instance variable created
emp.name= "JAMES";
emp.address = "JAMES ADDRESS";
}
}
Organization
正在创建一个员工实例(它将自己的一组值分配给员工)类似地,
Organization2
也在创建一个雇员实例(它将自己的一组值分配给雇员)题:
由于这是两个不同的实例。这里的封装如何违反?
最佳答案
Employee
类的封装被违反。变量name
和address
是公共的。应该将它们设置为private
,并应为其定义吸气剂和吸气剂。