定义一个Person类,含姓名、性别、年龄等字段;继承Person类设计Teacher类,增加职称、部门等字段;继承Person类设计Student类,增加学号、入学时间、专业等字段。定义各类的构造方法和toString()方法,并分别创建对象进行测试。
源代码如下:
package pk1;
class Person{
String name,gender;
int age;
public Person(String name,String gender,int age) {
this.name=name;
this.gender=gender;
this.age=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);
System.out.println(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);
this.post=post;
this.branch=branch;
}
public String toString() {
return super.toString()+"职称:"+post+"部门:"+branch;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Teacher T=new Teacher("楚人美","女",25,"高级","戏曲");
System.out.println(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);
this.num=num;
this.date=date;
this.major=major;
}
public String toString() {
return super.toString()+"学号:"+num+"入学日期:"+date+"专业:"+major;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Student S=new Student("李强","男",8,"321","1988.9.1","生物");
System.out.println(S);
}
}
版权归原作者 最愚蠢的浪漫 所有, 如有侵权,请联系我们删除。