继承就是子类继承父类的特征和行为
继承的关键字:extends
一个子类只能继承一个父类,不支持多继承
可以对父类的方法进行重写
提高了类之间的耦合性
格式:
class 父类 {
}
class 子类 extends 父类 {
}
例:
Employee.java
public class Employee {
private String name;
private Double salary;
public Employee() {
}
public Employee(String name, Double salary) {
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", salary=" + salary +
'}';
}
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 void upSalary(double percent){
double raise = salary*percent/100;
salary+=raise;
}
}
Manager.java
public class Manager extends Employee{
private Double bonus;
public Manager(String name, Double salary) {
super(name, salary);
bonus = 0.0;
}
public Double getSalary(){
double baseSalary = super.getSalary();
return baseSalary+=bonus;
}
public Double getBonus() {
return bonus;
}
public void setBonus(Double bonus) {
this.bonus = bonus;
}
}
使用ArrayList进行存储数据,并使用增强for和迭代器进行遍历,
public class Demo01Test {
public static void main(String[] args) {
Manager boss = new Manager("hetl",9967.0);
boss.setBonus(1299.9);
System.out.println(boss.getSalary());
ArrayList<Employee> arr = new ArrayList<Employee>();
arr.add(boss);
arr.add(new Employee("hetl01",8999.0));
arr.add(new Employee("hetl02",10999.0));
for (Employee e:arr){
System.out.println(e);
}
System.out.println("==========");
Iterator<Employee> it = arr.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
}
输出
11266.9
Employee{name='hetl', salary=9967.0}
Employee{name='hetl01', salary=8999.0}
Employee{name='hetl02', salary=10999.0}
==========
Employee{name='hetl', salary=9967.0}
Employee{name='hetl01', salary=8999.0}
Employee{name='hetl02', salary=10999.0}