定义一个Person类,含姓名、性别、年龄等字段;

时间:2025-04-02 08:13:37

定义一个Person类,含姓名、性别、年龄等字段;继承Person类设计Teacher类,增加职称、部门等字段;继承Person类设计Student类,增加学号、入学时间、专业等字段。定义各类的构造方法和toString()方法,并分别创建对象进行测试。

源代码如下:

package pk1;
class Person{
     String name,gender;
    int age;
   
     public Person(String name,String gender,int age) {
         =name;
         =gender;
         =age;
     }//有参构造方法
     
     public Person(){
         this("","",0);
     }//无参构造方法
     
     public String toString() {
         return "姓名:"+name+"性别:"+gender+"年龄"+age;
     }
     
     public static void main(String[] args) {
         // TODO Auto-generated method stub
        Person P=new Person("李华","男",23);
        (P);
     }
}
public class Teacher extends Person {
     String post,branch;
     public Teacher(String name,String gender,int age,String post,String branch) {
         super(name,gender,age);
         =post;
         =branch;
     }
     
     public String toString() {
         return ()+"职称:"+post+"部门:"+branch;
     }
     public static void main(String[] args) {
         // TODO Auto-generated method stub
        Teacher T=new Teacher("楚人美","女",25,"高级","戏曲");
        (T);
     }
}
class Student extends Person{
     String num,date,major;
     
     public Student(String name,String gender,int age,String num,String date,String major) {
         super(name,gender,age);
         =num;
         =date;
         =major;
     }
     
     public String toString() {
         return ()+"学号:"+num+"入学日期:"+date+"专业:"+major;
     }
     
     public static void main(String[] args) {
         // TODO Auto-generated method stub
        Student S=new Student("李强","男",8,"321","1988.9.1","生物");
        (S);
     }
}

相关文章