代码实现
首先定义Person类(人类)
/**
* 人的基础特征
*
* @author Admin
*/
public class Person {
/**
* 姓名
*/
String name;
/**
* 生日
*/
Date birthday;
/**
* 手机号码
*/
String tel;
/**
* 身份证号码
*/
String idCode;
public Person() {
}
public Person(String name, Date birthday, String tel, String idCode) {
this.name = name;
this.birthday = birthday;
this.tel = tel;
this.idCode = idCode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getIdCode() {
return idCode;
}
public void setIdCode(String idCode) {
this.idCode = idCode;
}
}
其次,定义Student类(学生类)继承Person类(人类)
/**
* 学生的基本特征
*
* @author Admin
*/
public class Student extends Person {
/**
* 学号
*/
private String studentId;
public Student() {
}
public Student(String name, Date birthday, String tel, String idCode) {
super(name, birthday, tel, idCode);
}
public Student(String name, Date birthday, String tel, String idCode, String studentId) {
super(name, birthday, tel, idCode);
this.studentId = studentId;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
}
最后,调用Student全参构造方法测试
public class Test {
public static void main(String[] args) {
Student student = new Student("张三",
new Date(),
"10086",
UUID.randomUUID().toString(),
System.currentTimeMillis() + "");
System.out.println("名字:" + student.getName());
System.out.println("生日:" + student.getBirthday());
System.out.println("手机号码:" + student.getTel());
System.out.println("身份证号:" + student.getIdCode());
System.out.println("学号:" + student.getStudentId());
}
}
什么是super
在派生类(子类)中想要调用超类(父类)的属性或方法是,用super代指超类对象,例如当前类的属性名与超类的属性名相同,为了便于区分,引入super关键字,示例如下:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Student extends Person {
private String name;
public Student(String name, String name1) {
super(name); // 调用父类构造方法
this.name = name1;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
}