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

Ran*_* B. 3 java methods class

下面是我困惑的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);
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*oun 5

我建议您浏览一下有关定义方法的链接.

  • public Student searchStudent(Student student)

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

  • public Student searchStudent(int id)

    同样,但它接受的参数是int.在这里你可以搜索student不是对象本身,而是由IDstudent.

  • public boolean addStudent(Student student)

    这是一个向ArrayList 添加student(类型Student)的方法students.

提示:在调试模式下运行代码并按照您不理解的每种方法,您会惊讶于这将有助于您更好地理解程序的流程.