程序员3个属性:姓名,年龄,工资
经理:包括上面三个属性,还有奖金属性
继承思想设计类,类中提供必要的方法进行属性访问
public class Test {
public static void main(String [] args) {
Coder c = new Coder("张三",18,5000);
c.work();
Manager m = new Manager("张三",18,5000,500);
m.work();
}
}
abstract class Employee {
private String name; //姓名
private int age; //年龄
private double salary; //奖金
public Employee() {} //空参构造
public Employee(String name,int age, double salary) { //有参构造
this.name = name;
this.age = age;
this.salary = salary;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getSalary() {
return salary;
}
public abstract void work(); //抽象方法
}
class Coder extends Employee {
public Coder() {}
public Coder(String name,int age,double salary) {
super(name,age,salary); //初始化父类参数
}
public void work() {
System.out.println("我的姓名是:" + super.getName() + ",我的年龄是:" + this.getAge() + ",我的工资是:" + this.getSalary());
}
}
class Manager extends Employee {
private double bonus;
public Manager() {}
public Manager(String name,int age,double salary,double bonus) {
super(name,age,salary); //父类属性用super
this.bonus = bonus; //当前属性用this,在此类用this代表当前引用对象赋值
}
public void work() {
System.out.println("我的姓名是:" + this.getName() + ",我的年龄是:" + this.getAge() + ",我的工资是:" + this.getSalary() + ",我的奖金是:" + this.bonus);
}
}