我正在尝试测试封装,如果我调用新的 Obj 进行测试,这算不算?



我正在尝试测试封装。

我做了两个对象部门和员工。

部门通过员工实例,然后测试封装,我遵循这些规则

1.显示员工详细信息

2.显示部门详细信息

3.更改员工对象中的值

4.再次显示部门详细信息(信息不应更改(

5.再次显示员工详细信息(信息应在此处更改(。

这有效,但我是否通过创建 employee1 的新实例来理解封装的想法????

我应该为真正的封装设置值吗

employee1.setName("Sam")

这会将部门名称的第二个 display(( 调用更改为 Sam。

//Main
package question1;
public class Test {
public static void main(String[] args) {
//Creating a instance of both Employee and Department
Employee employee1 = new Employee("2726354E", "Bob Ings", 30000 );
Department mainDepartment = new Department("Main Floor", employee1);
//Displaying both instances of Employee and Department
employee1.display();    
mainDepartment.display();
System.out.println("");     

//Changing values in constructor for the instance of Employee we made earlier on 
employee1 = new Employee("626347B", "Sam O'Conor", 24000);
mainDepartment.display();
System.out.println("");     
System.out.println("");
employee1.display();
}
}

//Employee Class
package question1;
public class Employee {
private String ppsNum;
private String name;
private double salary;
//Parameterized constructor 
public Employee(String ppsNum, String name, double salary) {
this.ppsNum = ppsNum;
this.name = name;
this.salary = salary;
}
//Displaying the instance of the object information in a anesthetically pleasing manner
public void display() {
System.out.println("Employee Information");
seperationLine();
System.out.println("Name: " + getName());
seperationLine();
System.out.println("PPS number: " + getPpsNum());
seperationLine();
System.out.println("Salary: " + getSalary() + "0");
seperationLine();
System.out.println("n");

}}
//Department Class
package question1;
public class Department {
private String deptName;
private Employee employee;
private int officeNumber;
//Constructor with all three parameters 
public Department(String deptName, Employee employee, int officeNumber) {
this.deptName = deptName;
this.employee = employee;
this.officeNumber = officeNumber;
}
//Constructor with the officeNumber set to 0
public Department(String deptName, Employee employee) {
this.deptName = deptName;
this.employee = employee;
this.officeNumber = 0;
}
//Displaying the instance of the object information in a anesthetically pleasing manner
public void display() {
System.out.println("Department");
Employee.seperationLine();
System.out.println("Department Name: " + getDeptName());
Employee.seperationLine();
System.out.println("Employee: " + employee.toString());
Employee.seperationLine();
System.out.println("Office Number: " + getOfficeNumber());
}
}

没有"测试"封装这样的东西。

您无需编写任何代码来确定您的类是否正确遵循封装原则。封装是面向对象的分析和设计指南。不是编程功能。


良好的封装意味着您遵循两个步骤:

  1. 所有相关信息应放在一起。例如:员工应该只有员工信息,部门应该只有部门信息。员工不应该存储特定部门所在的楼层。或者甚至不应该有一个名为seperationLine((的方法。(IMO,seperationLine(( 方法属于另一个 Presentor 类(
  2. 只应公开所需的信息。其余的都应该是私人的或受保护的。目标不是保密,而是防止外部参与者修改他们不应该修改的信息的潜在问题。例如:员工不应设置部门楼层。

只需查看 Employee 类,并将您认为不应在外部访问的所有字段和方法设置为私有。此外,对于部门需要从员工那里获得的信息,请在员工类中创建一个部门可以调用的方法。这样,员工就不能按部门修改,但它可以访问所需的信息。

最新更新