问题描述
目前我有两节课。课堂班和学校班。我想在School类中编写一个方法来从教室类调用public void setTeacherName(String newTeacherName)。
Currently I have two classes. a classroom class and a School class. I would like to write a method in the School class to call public void setTeacherName(String newTeacherName) from the classroom class.
classroom.java
public class classroom {
private String classRoomName;
private String teacherName;
public void setClassRoomName(String newClassRoomName) {
classRoomName = newClassRoomName;
}
public String returnClassRoomName() {
return classRoomName;
}
public void setTeacherName(String newTeacherName) {
teacherName = newTeacherName;
}
public String returnTeacherName() {
return teacherName;
}
}
School.java
import java.util.ArrayList;
public class School {
private ArrayList<classroom> classrooms;
private String classRoomName;
private String teacherName;
public School() {
classrooms = new ArrayList<classroom>();
}
public void addClassRoom(classroom newClassRoom, String theClassRoomName) {
classrooms.add(newClassRoom);
classRoomName = theClassRoomName;
}
// how to write a method to add a teacher to the classroom by using the
// classroom parameter
// and the teachers name
}
推荐答案
您应该将类的名称大写。在你的课堂上这样做之后,
You should capitalize names of your classes. After doing that do this in your school class,
Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);
此外,我建议您使用某种IDE,例如eclipse,它可以帮助您例如,代码为您生成getter和setter。例如:右键单击Source - > Generate getters and setters
Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters
这篇关于如何在Java中调用另一个类中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!