Student类
public class Student {
protected String name;
protected String num;
protected int age;
protected static int studentCount = 0;
public Student() {
}
public Student(String name, String num, int age) {
this.name = name;
this.num = num;
this.age = age;
studentCount++;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "学生 [姓名:" + name + ", \n\t学号:" + num + ", \n\t年龄:" + age + ", \n\t学生个数: " + studentCount +"]";
}
@Override
protected void finalize() throws Throwable {
studentCount--;
//super.finalize();
}
}
CollegeStudent类
public class CollegeStudent extends Student {
protected String profession;
public CollegeStudent(String name, String num, int age,String profession) {
super(name, num, age);
this.profession = profession;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
@Override
public String toString() {
return (super.toString() + "\t专业 " + this.profession);
}
}
测试类StudentTest
public class StudentTest {
public static void main(String[] args) {
Student s1 = new Student("Tom","0640000001",22);
System.out.println(s1);
s1.setName("Tim");
s1.setAge(23);
System.out.println(s1);
System.out.println("当前学生对象数量:" + Student.studentCount);
{
Student s2 = new Student("张三","0640000002", 21);
System.out.println(s2);
Student s3 = new Student( "李四", "0641100004",22);
System.out.println(s3);
System.out.println("当前学生对象数量:" + Student.studentCount);
}
System.out.println("当前学生对象数量:" + Student.studentCount);
CollegeStudent cc1 = new CollegeStudent("王五","0640000010", 25, "计算机应用");
System.out.println(cc1);
CollegeStudent cc2 = new CollegeStudent("赵六","0640000012", 28, "嵌入式系统开发");
System.out.println(cc2);
System.out.println("当前大学生对象数量:" + CollegeStudent.studentCount);
cc2.setProfession("商务管理");
System.out.println("赵六改了专业\n" + cc2);
}
}
运行结果为