定义一个Person类,含姓名、性别、年龄等字段;继承Person类设计Teacher类,增加职称、部门等字段;继承Person类设计Student类,增加学号、入学时间、专业等字段。定义各类的构造方法和toString()方法,并分别创建对象进行测试。文章来源:https://www.toymoban.com/news/detail-504685.html
源代码如下:文章来源地址https://www.toymoban.com/news/detail-504685.html
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);
}
}
到了这里,关于定义一个Person类,含姓名、性别、年龄等字段;的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!