1. 我们先定义一个抽象人类,命名为AbstactPerson
1. 类继承使用关键字extends, 在java中类只能单继承
2. 一个类用abstract修饰, 那么这个类就是抽象类
3. 抽象类可以继承其他类和接口, 而且不需要实现或者重写其中的方法
4. 抽象类不能实例化, 实例化的话只能使用匿名内部类 , 但是可以声明一个抽象类的引用
5. 如果一个子类没有实现抽象父类所有的abstract方法,那么这个子类必须要定义为抽象类
6. 当一个非抽象子类实现了其抽象父类所有abstract方法(包括父类的父类中的abstract方法, 父类实现的接口中的abstract方法), 这个子类就可以定义为普通类
7. abstract不能与static、private、final一起修饰方法,因为这些方法不能被重写
8. abstract不能作用与final,因为final类不能被继承
public abstract class AbstactPerson {
private Integer id;
private String name;
public AbstactPerson(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstractvoid eat();
}
2. 我们先定义一个抽象员工类,命名为Employee
1. super关键字,主要是作用于子类的方法中, 用于指向父类对象, 可以
2. 访问父类的属性、调用父类的普通方法和构造方法
3. 子类的构造函数第一行会默认调用父类无参的构造函数,及隐式调用super();
4. 如果父类中没有无参构造器 , 那么必须显示调用super的有参构造方法
5. super不能赋值给变量, 它只是一个指示编译器调用超类方法的特殊关键字。
public abstract class AbstactEmployee extends AbstactPerson {
private String company;
public AbstactEmployee(Integer id, String name) {
super(id, name);
}
public AbstactEmployee(Integer id, String name, String company) {
super(id,name);
this.company = company;
}
public abstractvoid eat();
}
3. 我们先定义一个学生类,命名为Student
1. this关键字指向当前对象本身, 可以赋值给其他变量
2. this可以调用当前类中的属性、普通方法和构造方法
3. 当形参和成员变量名称一样的时候,可以用this区分
public class Student extends AbstactPerson {
private String school;
public Student(Integer id, String name) {
super(id, name);
}
public Student(Integer id, String name, String school) {
this(id, name);
this.school = school;
}
@Override
public void eat() {
System.out.println("在学校食堂吃饭");
}
}