定义一个Student类,继承Person类,有String类型的属性ID和int类型的属性classes。 定义无参构造器,每次无参构造器被调用会在控制台打印"创建一名学生。 定义有参构造器,构造器有String类型的形参name,String类型的形参gender,int类型的形参age,String类型的形参ID和int类型的形参classes,调用此构造器首先会使用name、gender和age三个形参通过super关键字调用父类构造器赋值,再利用形参和this关键字为此对象的ID届属性和 classes届性赋值。 定义Test类,在其中定义main方法。在main方法中首先使用无参构造器获得Teacher类对象t和Student类对象s,再使用一名你熟悉的学校老师的信息和你自己以及一位你的室友的信息,得到另外的Teacher对象 (t1)和2位Student对象 (s1和s2)。打印输出对象信息,每行一人。
时间: 2023-01-28 14:45:11 浏览: 122
在 Java 中,你可以这样定义一个 Student 类:
```
public class Student extends Person {
private String ID;
private int classes;
public Student() {
System.out.println("创建一名学生。");
}
public Student(String name, String gender, int age, String ID, int classes) {
super(name, gender, age);
this.ID = ID;
this.classes = classes;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public int getClasses() {
return classes;
}
public void setClasses(int classes) {
this.classes = classes;
}
}
```
在 Test 类中,你可以这样使用这个类:
```
public class Test {
public static void main(String[] args) {
Teacher t = new Teacher();
Student s = new Student();
Teacher t1 = new Teacher("张老师", "男", 45, "数学");
Student s1 = new Student("张三", "男", 20, "1001", 1);
Student s2 = new Student("李四", "男", 21, "1002", 2);
System.out.println(t.getName() + " " + t.getGender() + " " + t.getAge() + " " + t.getSubject());
System.out.println(s.getName() + " " + s.getGender() + " " + s.getAge() + " " + s.getID() + " " + s.getClasses());
System.out.println(t1.getName() + " " + t1.getGender() + " " + t1.getAge() + " " + t1.getSubject());
System.out.println(s1.getName() + " " + s1.getGender() + " " + s1.getAge() + " " + s1.getID() + " " + s1.getClasses());
System.out.println(s2.getName() + " " + s2.getGender() + " " + s2.getAge() + " " + s2.getID() + " " + s2.getClasses());
}
}
```
阅读全文