首页 > 解决方案 > 如何在Java中的一个类中调用另一个类的方法

问题描述

我正在尝试使用我在 class 中创建的方法Student,在另一个类中,Classroom. 我想知道是否甚至可以调用在另一个类中定义的方法,或者我是否以错误的方式接近这个。

Student

public class Student {
    String firstName;

    Student(String firstName){
        this.firstName=firstName;
    }

    public String getFirstName() {
        return firstName;
    }
}

Classroom

public class Classroom{

    public ArrayList<Student> students;

    public Classroom(ArrayList<Student> studentArrayList) {

    }

    Student getStudent(ArrayList students){
        this.students=students;
        System.out.println(students.get(0).getFirstName);
        return null;
    }
}

Main

public class Main {

    public static void main(String[] args) {
        Student a = new Student("John");
        Student b = new Student("Jane");

        ArrayList<Student> studentArrayList = null;
        studentArrayList.add(a);
        studentArrayList.add(b);

        Classroom c = new Classroom(studentArrayList);

        System.out.println(c.getStudent(studentArrayList));
    }
}

我的问题似乎是当我尝试调用该方法getFirstName时,我想知道是否有一种方法可以getFirstNameClassroom类中调用。我对这段代码的意图是返回 object a

标签: javamethods

解决方案


问题是,你忘了getFirstName()Classroom类后面加上括号,而且,你应该在构造函数中初始化students

它应该是这样的:

public class Classroom {

    public ArrayList<Student> students;

    public Classroom(ArrayList<Student> studentArrayList) {
        students = studentArrayList
        // you can add other code here
    }

    Student getStudent(int index) {
        // get the first name of the student at the given index
        System.out.println(students.get(index).getFirstName());
        return students.get(index); // return the Student object instead of null
    }
}

然后,在Main课堂上:

public class Main {

    public static void main(String[] args) {
        Student a = new Student("John");
        Student b = new Student("Jane");

        ArrayList<Student> studentArrayList = new ArrayList<Student>();
        studentArrayList.add(a);
        studentArrayList.add(b);

        Classroom c = new Classroom(studentArrayList); // now the students ArrayList is initialized

        System.out.println(c.getStudent(0)); // replace 0 with the index you want
    }
}

您可以保持Student课程不变。


推荐阅读