示例
抽象类Person如下,包含一些构造器、属性、两个抽象方法、一个普通方法:
public abstract class Person {
/**
* 姓名
*/
String name;
/**
* 生日
*/
Date birthday;
/**
* 性别
*/
Integer gender;
/**
* 住址
*/
String address;
public Person() {
}
public Person(String name, Date birthday, Integer gender, String address) {
this.name = name;
this.birthday = birthday;
this.gender = gender;
this.address = address;
}
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 Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
/**
* 自我介绍
*/
abstract void selfIntroduction();
/**
* 打招呼
*/
abstract void greetSomeBody();
/**
* 运动
*/
void sport(){
System.out.println(name + "正在做运动");
}
}
实现类Student如下 ,实现了父类Person中声明的两个方法:
public class Student extends Person {
private String studentID;
public Student() {
}
public Student(String name, Date birthday, Integer gender, String address, String studentID) {
super(name, birthday, gender, address);
this.studentID = studentID;
}
@Override
public void selfIntroduction() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("老师、同学们好,我叫");
stringBuilder.append(super.name);
stringBuilder.append(",我来自");
stringBuilder.append(super.address);
System.out.println(stringBuilder);
}
@Override
public void greetSomeBody() {
System.out.println("哈喽哈喽");
}
}
测试类如下,创建了Student对象,执行了全部方法
public class Test {
public static void main(String[] args) {
Student student = new Student("张三", new Date(), 1, "鞍山市", UUID.randomUUID().toString());
student.selfIntroduction();
student.greetSomeBody();
student.sport();
}
}