9.java抽象类的使用
程序员文章站
2024-03-23 09:44:22
...
#1.有父类Employee,有成员经理manager和程序员coder
#因为父类中有共同的name,salary,id,work(),但是各不相同,所以方法可以定义为抽象方法
#其中Manager继承Employee, 有bonus和work()
#coder继承Employee, 有work()
#父类Employee
public abstract class Employee {
//抽象类的成员变量
private String name;
private double salary;
private String id;
//无参构造方法
public Employee() {
}
//getter和setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
//有参构造方法
public Employee(String name, double salary, String id) {
this.name = name;
this.salary = salary;
this.id = id;
}
//成员方法
public abstract void work();
}
}
#子类Manager类
public class Manager extends Employee {
//成员变量
private int bonus;
//getter和setter方法
public int getBonus() {
return bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}
//无参构造器
public Manager() {
}
//有参构造器
public Manager(String name, double salary, String id, int bonus) {
super(name, salary, id);
this.bonus = bonus;
}
//重写父类的成员方法
@Override
public void work() {
System.out.println("经理在工作");
}
}
#子类coder类
public class Coder extends Employee {
@Override
public void work() {
System.out.println("程序员要敲代码");
}
}
#测试运行
public class TestDemo1 {
public static void main(String[] args) {
//创建多态程序员对象em
Employee em = new Coder();
em.work();
//创建多态经理对象em2
Employee em2 = new Manager("王五",60000,"研发部02",50000);
em2.work();
//下面是coder以面对对象的方式
Coder c = new Coder();
c.setName("张三");
c.setSalary(30000);
c.setId("研发部");
System.out.println("姓名:"+c.getName());
System.out.println("薪水:"+c.getSalary());
System.out.println("部门:"+c.getId());
//Manger对象测试
Manager m = new Manager("李四",40000,"研发部01",10000);
System.out.println("姓名:"+m.getName());
System.out.println("薪水:"+m.getSalary());
System.out.println("部门:"+m.getId());
System.out.println("奖金:"+m.getBonus());
}
}
下一篇: ESP8266列出文件目录