问题定义:假设人分为学生和工人,学生和工人都可以说话,但是学生和工人说话的内容是不一样的,也就是说说话这个功能应该是一个具体功能,而说话的内容就要由学生或工人来决定了。可以使用抽象类来实现这个功能。输出结果:abstract class Person{ //定义一个抽象类Person private String name; //name属性 private int age; //age属性 public Person(String name, int age){ //构造方法 this.setName(name); this.setAge(age); } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public void setAge(int age){ this.age =age; } public int getAge(){ return this.age; } public void say(){ //说话方法 System.out.println(this.getContext()); } public abstract String getContext();//返回人说话内容的方法,具体由子类来实现 }; class Student extends Person{ //学生类继承Person类,并且实现getContext方法 private float score; public Student(String name,int age,float score){ super(name,age); setScore(score); } public void setScore(float score){ this.score = score; } public float getScore(){ return this.score; } public String getContext(){ //实现getContext方法 return "name = " + super.getName() + ", age = " + super.getAge() + ", score = " + this.getScore(); } }; class Worker extends Person{ //工人类实现Person类,并且实现getContext方法 private float salary; public Worker(String name,int age,float salary){ super(name,age); setSalary(salary); } public void setSalary(float salary){ this.salary = salary; } public float getSalary(){ return this.salary; } public String getContext(){ return "name = " + super.getName() + ", age = " + super.getAge() + ", salary = " + this.getSalary(); } }; public class AbstractCaseDemo02{ public static void main(String agrs[]){ Person per1 = null; Person per2 = null; per1 = new Student("Tom",20,98.0f);//定义学生对象 per2 = new Worker("Jay",34,5600.0f);//定义工人对象 per1.say(); per2.say(); } };
name = Tom, age = 20, score = 98.0
name = Jay, age = 34, salary = 5600.0
抽象类的应用-定义模板
最新推荐文章于 2021-12-02 18:31:55 发布