JAVA编写学生类和老师类,并通过测试类创建对象进行测试
时间: 2024-05-23 11:09:15 浏览: 145
创建学生(Student)类,并实例化对象访问测试
5星 · 资源好评率100%
好的,我知道你想问什么。下面是JAVA编写学生类和老师类的示例代码:
// 学生类
public class Student {
private String id;
private String name;
private int age;
// 构造方法
public Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// getter和setter方法
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
// 老师类
public class Teacher {
private String id;
private String name;
private int age;
private String[] courses;
// 构造方法
public Teacher(String id, String name, int age, String[] courses) {
this.id = id;
this.name = name;
this.age = age;
this.courses = courses;
}
// getter和setter方法
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getCourses() {
return courses;
}
public void setCourses(String[] courses) {
this.courses = courses;
}
}
// 测试类
public class Test {
public static void main(String[] args) {
// 创建学生对象并测试
Student student = new Student("001", "张三", 18);
System.out.println("学生信息:");
System.out.println("ID:" + student.getId());
System.out.println("姓名:" + student.getName());
System.out.println("年龄:" + student.getAge());
// 创建老师对象并测试
String[] courses = {"Java", "Python", "C++"};
Teacher teacher = new Teacher("T001", "李四", 35, courses);
System.out.println("老师信息:");
System.out.println("ID:" + teacher.getId());
System.out.println("姓名:" + teacher.getName());
System.out.println("年龄:" + teacher.getAge());
System.out.println("教授课程:");
for (String course : teacher.getCourses()) {
System.out.println(course);
}
}
}
希望这可以回答你的问题。如果你还有什么问题,请尽管问我。
阅读全文