JAVA类和对象练习
①定义类Teacher,属性name,subject,行为teach,构造函数初始化两个属性。
②定义类Student,属性name,grade,行为study,构造函数初始化两个属性。
③定义类ClassRoom,属性Teacher,Student[],构造函数初始化两个属性,行为showMembers()输出教师和学生的名字
class Teacher {
String name;
String subject;
public Teacher(String name, String subject) {
this.name = name;
this.subject = subject;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void teach() {
System.out.println(this.name + " is teaching " + this.subject);
}
}
class Student {
String name;
int grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
public void study() {
System.out.println(this.name + " is studying in grade " + this.grade);
}
}
class ClassRoom {
Teacher teacher;
Student[] students;
public ClassRoom(Teacher teacher, Student[] students) {
this.teacher = teacher;
this.students = students;
}
public void showMembers() {
System.out.print(this.teacher.getName()+",");
int size = this.students.length;
for (int i = 0; i < size; i++) {
System.out.print(this.students[i].getName());
if (i < size - 1) {
System.out.print(",");
}
}
System.out.println();
}
}
public class Test {
public static void main(String[] args) {
Teacher teacher = new Teacher("Viktor Axelsen", "Badminton");
Student[] students = new Student[2];
students[0] = new Student("Shi Yuqi", 1);
students[1] = new Student("Lee Zijia", 2);
ClassRoom classRoom = new ClassRoom(teacher, students);
classRoom.showMembers();
}
}
注意下输出格式,可以按需更改。