Java 定义一个Person类,有姓名、年龄两个属性。再定义一个Student类继承Person类,Student类除了继承人类的属性外,还有学生学号、班级、所学课程等属性,并且实现学习的行为。再定义一个测试类,用于测试学生类。
时间: 2024-12-26 09:30:52 浏览: 9
在Java中,我们可以按照这样的结构来定义:
```java
// Person类,基础类
public class Person {
private String name;
private int age;
// 构造函数和getter/setter方法
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getters and setters
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; }
}
// Student类,继承自Person并添加额外属性和行为
public class Student extends Person {
private String studentID;
private String className;
private List<String> courses;
// 学习方法
public void study(String course) {
System.out.println("学生 " + getName() + " 正在学习 " + course);
}
// 构造函数和getter/setter方法
public Student(String name, int age, String studentID, String className, List<String> courses) {
super(name, age); // 调用父类构造函数
this.studentID = studentID;
this.className = className;
this.courses = courses;
}
// getters and setters for additional properties
public String getStudentID() { return studentID; }
public void setStudentID(String studentID) { this.studentID = studentID; }
public String getClassName() { return className; }
public void setClassName(String className) { this.className = className; }
public List<String> getCourses() { return courses; }
public void setCourses(List<String> courses) { this.courses = courses; }
}
// Test类,用于测试Student类
public class TestStudent {
public static void main(String[] args) {
// 创建一个Student对象并设置属性
Student student = new Student("张三", 18, "001", "一班", Arrays.asList("数学", "英语"));
// 调用父类和子类的方法
System.out.println("姓名: " + student.getName());
System.out.println("年龄: " + student.getAge());
// 测试学习行为
student.study("物理");
}
}
```
阅读全文