繼承:經過擴展一個已經存在的類而造成的一個新類,在這個新類中,自動存在父類中的域和方法,而且能夠有本身獨特的域和方法。ide
1.建立一個類測試
public class Employee { private String name; private double salary; private LocalDate hireDate; public Employee(String name,double salary,int year,int month,int days) { this.name=name; this.salary=salary; hireDate=LocalDate.of(year,month,days); } public String getName() { return name; } public double getSalary() { return salary; } public LocalDate getHireDate() { return hireDate; } public void raiseSalary(double byPercent){ double raise=salary*byPercent/100; salary+=raise; } }
2.建立子類this
public class Manager extends Employee{ private double bonus; public Manager(String name,double salary,int year,int month,int days) { super(name,salary,year,month,days); bonus=0; } @Override public double getSalary() { return super.getSalary()+bonus; } public double getBonus() { return bonus; } public void setBonus(double bonus) { this.bonus = bonus; } }
Note:spa
測試:code
public class TestSubClass { public static void main(String[] args) { Manager manager=new Manager("liuchen",5000.0,2018,6,25); manager.setBonus(2000.0); Employee[] e=new Employee[3]; e[0]=manager; //引用的Manager對象 e[1]=new Employee("zhangsan",2000.0,2018,5,25); e[2]=new Employee("lisi",2000.0,2018,5,27); for(Employee em:e) { System.out.print(em.getName()+"-->"+em.getSalary()+"-->"+em.getHireDate()); } } }
運行結果:對象
liuchen-->7000.0-->2018-06-25
zhangsan-->2000.0-->2018-05-25
lisi-->2000.0-->2018-05-27blog
能夠看到,子類對象正確的調用了getSalary(),由於e[0]引用的是Manager對象。繼承