java - 如何在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
时,我想知道是否有一种方法可以getFirstName
在Classroom
类中调用。我对这段代码的意图是返回 object a
。
解决方案
问题是,你忘了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
课程不变。
推荐阅读
- typescript - Typescript : @SerializedName("OO00") 在像 Gson 这样的 TypeScript 界面中
- c - 为什么文件指针的行为与 C 语言中的普通指针不同?
- javascript - Express Session 过期时间和日期设置错误
- java - 如何下载和导入openjdk-11测试包
- microservices - 如何将 ER 图表划分为多个微服务
- richtextbox - 如何从 Visual Studio 获取 RichTextBox OCX
- python - 使用 python 打印 youtube 标题的问题
- stan - 替代 stan 中的数据填充
- flutter - 颤振在var中返回未来列表以在循环外使用
- udp - 如何在nestjs中创建UDP代理客户端