为什么方法使用类名作为修饰符(?)和参数?

时间:2013-09-23 06:24:53

标签: java class methods

以下是我困惑的4种方法,4种方法在Teacher类中。我有一个学生班和老师班。在Teacher类中,声明的是ArrayList<Student> students作为实例变量。

如何解释我在下面给出的方法中看到的学生,它也用作参数。我对Student searchStudent(在方法中)和Student student(在参数内)非常困惑。这仅适用于ArrayList吗?如何理解一个类使用类名搜索另一个类的概念?

public Student searchStudent(Student student)
{
    //confuses me
    Student found = null;

    if (this.students.contains(student))
    {
        int index = this.students.indexOf(student);
        if (index != -1)
        {
            found = this.students.get(index);
        }
    }
    return found;
}

public Student searchStudent(int id)
{
    //confuses me
    Student beingSearched = new Student();
    beingSearched.setStudentId(id);
    return this.searchStudent(beingSearched);
}

public boolean addStudent(Student student)
{
    //confuses me
    boolean added = false;
    if (this.searchStudent(student) == null)
    {
        this.students.add(student);
        added = true;
    }
    return added;
}

public boolean addStudent(int id, String name, double grade)
{
    //this is fine as i know boolen and int, String and double//
    Student student = new Student(id, name, grade);
    return this.addStudent(student);
}

1 个答案:

答案 0 :(得分:5)

我建议您通过this link了解定义方法

  • public Student searchStudent(Student student)

    这是一个public方法,它返回类型为Student的对象,它也接受类型为Student的对象。 它需要接受student参数,因为它会搜索它。当您想要搜索记录中是否存在某些student时(student ArrayList中),您将使用此方法。

  • public Student searchStudent(int id)

    相同,但它接受的参数是int。在这里,您将不是通过对象本身搜索student,而是通过student id 搜索。{/ p>

  • public boolean addStudent(Student student)

    这是一种向student ArrayList添加Student(类型为students)的方法。

提示:在 Debug 模式下运行您的代码,并按照您不理解的每种方法,您会惊讶于这将有助于您更好地了解程序的流程。< / p>