五:抽象类
现实中对一个群体的总结描述,例如中国人-陕西人-西安人-雁塔人
5.1 抽象关键字:abstract
该关键字可以适用于类、方法
方法中使用格式:
权限修饰符(一般情况都是public) abstract 返回值类型 方法名(形式参数列表)
类中使用格式:
abstract class 类名{}
5.2抽象类的特点
- 抽象类中不一定有抽象方法,但是有抽象方法的一应是抽象类
- 抽象方法是没有方法体的,需要继承的子类重写父类方法来实现该方法
- 抽象类是不能被实例化的。
- 抽象类实例化的方式:父类抽象类指向子类对象。Fu fu =new Zi();
5.3抽象方法的宗旨是
强制子类重写父类方法,具体功能子类实现。如果子类不重写父类的抽象方法,则子类会报错。非抽象方法可以不用重写
//父类
public abstract class people {
private String name;
private int age;
private String gender;
public people(){}
public people(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public abstract void sleep();
}
//教师类
public abstract class teacher extends people{
private String occupation;//职业
public teacher() {
}
public teacher(String occupation) {
this.occupation = occupation;
}
public teacher(String name, int age, String gender, String occupation) {
super(name, age, gender);
this.occupation = occupation;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
@Override
public void sleep() {
System.out.println("教师也需要睡觉");
}
public abstract void eat();
}
//高中老师类
public class highSchoolTeachers extends teacher {
public highSchoolTeachers() {
}
public highSchoolTeachers(String occupation) {
super(occupation);
}
public highSchoolTeachers(String name, int age, String gender, String occupation) {
super(name, age, gender, occupation);
}
@Override
public void eat() {
System.out.println("高中老师也需要吃饭");
}
public void selfIntroduction(){
System.out.println("大家好!我是:"+getName()+"\n"+"今年"+getAge()+"岁了。我的职业是"+"\""+
getOccupation()+"\"");
}
}
//测试类
public class testDemo {
public static void main(String[] args) {
teacher t = new highSchoolTeachers("高圆圆", 32, "女", "高中老师");
t.sleep();
t.eat();
//向下转型调用子类特有方法
highSchoolTeachers h= (highSchoolTeachers)t;
h.selfIntroduction();
}
}