定义一个抽象类Person,其中有一个公共的抽象方法showInfo()。然后定义此抽象类的一个子类Student,包括的成员变量有姓名、学号、班级和年龄,且此类中包括两个构造方法。
首先定义一个Student类,用来时实现Student中的一些成员属性,在Student类定义一个方法,用来输出成员变量中的一些信息,代码如下所示:
class Student {
String stuName;
String stuID;
String stuClass;
int age;
public Student(String stuName, String stuID) {
this.stuName = stuName;
this.stuID = stuID;
}
public Student(String stuName, String stuID, String stuClass, int age) {
this.stuName = stuName;
this.stuID = stuID;
this.stuClass = stuClass;
this.age = age;
}
public void showInfo() {
System.out.println("姓名:" + stuName + "\t" + "学号:" + stuID + "\t" + "班级:" + stuClass);
}
}
编写一个测试类,用来测试代码编写是否可以正常运行,通过测试类来测试输出学生的一些信息,如下图代码所示:
abstract class Persion {
public static void main(String args[]) {
Student student = new Student("张三", "2022140267", "计算机科学与技术", 18);
student.showInfo();
}
}
运行结果: