将变量从一个类传递到另一个类,而不更改方法名称

时间:2015-07-09 20:36:00

标签: java

我有一个课程需要在测试类中传递JUnit案例,因此方法名称getNumberStudents需要保持不变。

public class Course {

private Students students = null;

public Course(Students students, Grades grades) {
    this.students = students;
}
public int getNumberStudents() {
    int numberStudents = 0;     
    numberstudents = students.getNumberStudents();      
    return numberStudents;
}

但是,我需要使用另一个班级“学生”来访问数据。由于测试类的设置方式,我也无法修改此类中的方法签名。有人可以告诉我如何将我在Students课程中打印出的结果传递给Course课程吗?

public class Students {

public Students(String studentsDb) {
    try {
        FileInputStream file = new FileInputStream(new File(studentsDb));

        XSSFWorkbook workbook = new XSSFWorkbook(file);

        int numberStudents = 0;

        // Get first sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            if (row.getRowNum() == 0) {
                continue;
            }
            numberStudents = numberStudents + 1;
        }
        System.out.println(numberStudents);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

或者,有更简单的方法吗? 感谢。

1 个答案:

答案 0 :(得分:2)

你能做点什么:

public Class Students {
    private int numStudents;

    public Students(String studentsDb) {
        //Keep everything the same

        //add this line under the print statement:
        this.numStudents = numberStudents;
    }

    public int getNumberStudents() {
        return numStudents;
    }
}

然后在Course课程中,您现在可以students.getNumberStudents();