用java代码实现在上次类与对象习题的基础上再扩展。创建一个student类,类内含有姓名、性别和年龄等成员变量,定义获取各变量的方法和思考方法; 创建一个teacher类,类内含有姓名、性别和年龄等成员变量,定义获取各变量的方法和教学方法;创建一个people类,声明两个成员变量分别是student类和teacher类的对象,定义获取student类和teacher类中成员变量及思考和教学的方法;创建一个主类,主类中创建一个student对象,一个teacher对象和一个people对象。输出对象的相关信息。
时间: 2023-06-09 16:08:22 浏览: 126
阶段基础练习题.docx
以下是用Java代码实现在上次类与对象习题的基础上再扩展的答案:
```
class Student {
// 成员变量
private String name;
private String gender;
private int age;
// 构造函数
public Student(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
// 获取成员变量的方法
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
// 定义思考方法
public void think() {
System.out.println("I am thinking...");
}
}
class Teacher {
// 成员变量
private String name;
private String gender;
private int age;
// 构造函数
public Teacher(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
// 获取成员变量的方法
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
// 定义教学方法
public void teach() {
System.out.println("I am teaching...");
}
}
class People {
// 成员变量
private Student student;
private Teacher teacher;
// 构造函数
public People(Student student, Teacher teacher) {
this.student = student;
this.teacher = teacher;
}
// 获取成员变量的方法
public Student getStudent() {
return student;
}
public Teacher getTeacher() {
return teacher;
}
// 定义获取student类和teacher类中成员变量的方法
public String getStudentName() {
return student.getName();
}
public String getStudentGender() {
return student.getGender();
}
public int getStudentAge() {
return student.getAge();
}
public String getTeacherName() {
return teacher.getName();
}
public String getTeacherGender() {
return teacher.getGender();
}
public int getTeacherAge() {
return teacher.getAge();
}
// 定义思考和教学的方法
public void think() {
student.think();
}
public void teach() {
teacher.teach();
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("John", "Male", 18);
Teacher teacher = new Teacher("Mary", "Female", 35);
People people = new People(student, teacher);
// 输出对象的相关信息
System.out.println("Student name: " + people.getStudentName());
System.out.println("Student gender: " + people.getStudentGender());
System.out.println("Student age: " + people.getStudentAge());
System.out.println("Teacher name: " + people.getTeacherName());
System.out.println("Teacher gender: " + people.getTeacherGender());
System.out.println("Teacher age: " + people.getTeacherAge());
// 调用思考和教学的方法
people.think();
people.teach();
}
}
```
输出结果为:
```
Student name: John
Student gender: Male
Student age: 18
Teacher name: Mary
Teacher gender: Female
Teacher age: 35
I am thinking...
I am teaching...
```
阅读全文