我们为了使一个方法在继承中获得更高的层次,通常使用abstract关键字声明一个抽象类并将此方法声明为抽象方法放在抽象类中。
一个实例
public class PersonTest { public static void main(String[] args) { var people = new Person[2]; // fill the people array with Student and Employee objects people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1); people[1] = new Student("Maria Morris", "computer science"); // print out names and descriptions of all Person objects for (Person p : people) System.out.println(p.getName() + ", " + p.getDescription()); //p分别引用Student类与Employee类中的getDescription方法 } }
抽象类
package abstractClasses; public abstract class Person//我是一个抽象的类 { public abstract String getDescription();//我是一个抽象的方法 private String name; public Person(String name)//抽象类的构造器 { this.name = name; } public String getName()//我也是所有子类最基础的方法 { return name; } }
两个子类
public class Student extends Person { private String major; /** * @param name the student's name * @param major the student's major */ public Student(String name, String major) { super(name);//调用抽象类Person构造器,处理name this.major = major;//用Student的实例字段处理传入的参数变量 } public String getDescription() { return "a student majoring in " + major; } }
package abstractClasses; import java.time.*; public class Employee extends Person { private double salary; private LocalDate hireDay; public Employee(String name, double salary, int year, int month, int day) { super(name);//调用抽象类Person构造器,处理name this.salary = salary; hireDay = LocalDate.of(year, month, day); } public double getSalary() { return salary; } public LocalDate getHireDay() { return hireDay; } public String getDescription() { return String.format("an employee with a salary of $%.2f", salary); } public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } }