首页 / 操作系统 / Linux / Java 中关于抽象类和接口的范例
Java 中关于抽象类和接口的范例,通过多态中的向上转移实现。/*
*模板设计范例
*模拟人的两个实例学生和工人
*/
abstract class Person{ //人的模板,抽象类
private String name; //人的共同属性姓名
private int age; //人的共同属性年龄 public Person(String name,int age){ //构造初始化人的基本属性
this.name = name;
this.age = age;
} public String getName(){
return this.name;
}
public int getAge(){
return this.age;
} public void say(){ //人都有说话的功能
System.out.println(this.getContent());
} public abstract String getContent(); //抽象方法,人说出的话会不同}class Students extends Person{ //继承父类 private int score; public Students(String name,int age,int score){ //初始化“学生”这个人,有特有属性成绩
super(name,age); //调用父类构造初始化基本数据
this.score = score;
} public String getContent(){ //覆写抽象方法,即这个学生的行为
return "学生信息:"+"姓名:"+super.getName()+" 年龄:"+super.getAge()+" 成绩:"+this.score;
}
}class Workers extends Person{ //继承父类 private int salary;
public Workers(String name,int age,int salary){ //初始化“工人”这个人,有特有属性成绩
super(name,age); //调用父类构造初始化基本数据
this.salary = salary;
} public String getContent(){ //覆写抽象方法,即这个学生的行为
return "工人信息:"+"姓名:"+super.getName()+" 年龄:"+super.getAge()+" 薪水:"+this.salary;
}}public class Mbsj{
public static void main(String args[]){
Person p1 =null;
Person p2 =null;
p1 = new Students("张三",15,95); //采用对象的多态特性,向上转移
p2 = new Workers("李四",28,4000);
p1.say();
p2.say();
}
}本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-05/131217.htm