Java 抽象类经典例子3
目录
问题描述
抽象类的练习
学生案例:
具体类:一般员工 优秀员工
共性:姓名 工号 薪水
差异: 做事 奖金
代码块
代码块语法遵循标准markdown代码,例如:
//抽象类 employee
abstract class employee{
private String name;
private String id;
private int salary;
public employee(){}
public employee(String name,String id,int salary){
this.name=name;
this.id=id;
this.salary=salary;
}
public void setname(String name){
this.name=name;
}
public String getname(){
return name;
}
public void setid(String id){
this.id=id;
}
public String getid(){
return id;
}
public void setsalary(int salary){
this.salary=salary;
}
public int getsalary(){
return salary;
}
public abstract void work();
}
class Basicemployee extends employee{
public Basicemployee(){}
public Basicemployee(String name,String id,int salary){
super(name,id,salary);
}
public void work(){
System.out.println("做简单工作:");
}
}
class Goodempoyee extends employee{
private int money;
public Goodempoyee() {}
public Goodempoyee(String name,String id,int salary,int money){
super(name,id,salary);
this.money=money;
}
public void setmoney(int money){
this.money=money;
}
public int getmoney(){
return money;
}
public void work(){
System.out.println("做高级工作:");
}
}
class AbstractTest4{
public static void main(String[] args){
employee emp=new Basicemployee();
emp.setname("Basicemployee-1");
emp.setid("qwe0001");
emp.setsalary(10001);
System.out.println(emp.getname()+"----"+emp.getid()+"----"+emp.getsalary());
emp=new Basicemployee("Basicemployee-2","qwe0002",10002);
System.out.println(emp.getname()+"----"+emp.getid()+"----"+emp.getsalary());
//子类特有的要用一般的方法来调用,如果用多态则会报错
Goodempoyee emp2=new Goodempoyee();
emp2.setname("Goodempoyee-3");
emp2.setid("qwe0003");
emp2.setsalary(30000);
emp2.setmoney(10000);
System.out.println(emp2.getname()+"----"+emp2.getid()+"----"+emp2.getsalary()+"----"+emp2.getmoney());
}
}
答案
Basicemployee-1—-qwe0001—-10001
Basicemployee-2—-qwe0002—-10002
Goodempoyee-3—-qwe0003—-30000—-10000