-
参考 - P160~P161
-
主要有3个类: 一个测试类(ManagerTest)、一个子类(Manager)、一个父类(Employee)
-
注意点:
-1. 使用javac -d . *.java
进行预编译
目录结构入下:
此时会生成目录结构如下:
-
之后运行
java com.inheritance.ManagerTest
-
附上几个类的代码
// com.inheritance.Manager.java
package com.inheritance;public class Manager extends Employee{private double bonus;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;}
}
// com.inheritance.Employee.java
package com.inheritance;import java.time.*;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;}public LocalDate getHireDay() {return hireDay;}public void raiseSalary(double byPercent) {double raise = salary * byPercent / 100;salary += raise;}}
// com.inheritance.ManagerTest.java
package com.inheritance;public class ManagerTest {public static void main(String[] args) {Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);boss.setBonus(5000);Employee[] staff = new Employee[2];staff[0] = new Employee("Harry Hacher", 50000, 1989, 10, 1);staff[1] = new Employee("Tommy Tester", 40000, 1990, 3, 15);System.out.println("name: " + boss.getName() + ", salary: " + boss.getSalary());for(Employee e : staff) {System.out.println("name: " + e.getName() + ", salary: " + e.getSalary());}}
}