继承可以解决代码复用,让编程更加靠近人的思维。当多个类存在相同的属性(变量)和方法时,可以从这些类中抽象出父类,在父类中定义这些相同的属性和方法。所有的子类不需要重新定义这些属性和方法,只需要通过extends语句来声明继承父类:
class 子类 extends 父类
这样,子类就会自动拥有父类定义的属性和方法。
*父类的public修饰符的属性和方法,protected修饰符的属性和方法,默认修饰符的属性和方法被子类继承了,父类的private修饰符的属性和方法不能被子类继承。
注意事项:
- 子类最多只能继承一个父类
- java所有的类都是object类的子类
下面是由继承Employee 类来定义Manager 类的格式, 关键字extends 表示继承。
public class Manager extends Employee{ 添加方法和域}
子类中继承父类的域和方法;
子类构造器
public Manger(String name, double salary, int year, int month, int day){ super(name, salary, year, month, day); bonus = 0;}
因为子类终的构造器不能直接访问父类的私有域,所以必须利用父类的构造器对这部分私有域进行初始化,可以使用super实现对父类构造器的调用。使用super调用构造器的语句必须是子类构造器的第一条语句。
package testbotoo;
import java.time.LocalDate;
public class Employee
{
private String name;
private double salary;
private LocalDate hireDay;
public Employee(String name, double salary, int year, int month, int day)
{
this.name = name;
this.salary = salary;
hireDay = LocalDate.of(year, month, day);
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
}
package testbotoo;
public class Manager extends Employee
{
private double bonus;
/**
* @param name the employee's name
* @param salary the salary
* @param year the hire year
* @param month the dire onth
* @param day the hire day
*/
public Manager(String name, double salary, int year, int month, int day)
{
super(name, salary, year, month, day);
bonus = 0;
}
public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary +bonus;
}
public void setBonus(double b)
{
bonus = b;
}
}
package testbotoo;
public class ManagerTest {
public static void main(String[] args)
{
Manager boss = new Manager("aaa",8000,1999,12,20);
boss.setBonus(5000);
Employee[] staff = new Employee[3];
staff[0] = boss;
staff[1] = new Employee("hary",5000,1989,3,15);
staff[2] = new Employee("mayun",50000,1989,3,16);
for (Employee e : staff)
System.out.println("name="+e.getName()+",salary="+e.getSalary());
}
}