阅读量:0
在Java中,继承和多态是面向对象编程的两个重要特性。它们可以帮助我们更好地组织和管理代码,提高代码的可重用性和可扩展性。下面是一个关于Employee类的继承和多态应用的例子:
- 首先,我们创建一个基本的Employee类,包含一些基本属性和方法:
public class Employee { private String name; private int age; private double salary; public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } public void work() { System.out.println("Employee is working..."); } // Getter and Setter methods }
- 接下来,我们创建一个Manager类,继承自Employee类:
public class Manager extends Employee { private List<Employee> subordinates; public Manager(String name, int age, double salary) { super(name, age, salary); this.subordinates = new ArrayList<>(); } public void manage() { System.out.println("Manager is managing..."); } public void addSubordinate(Employee employee) { subordinates.add(employee); } // Other manager-specific methods }
在这个例子中,Manager类继承了Employee类的属性和方法。这意味着Manager对象可以访问和使用Employee类的所有属性和方法。同时,Manager类还有自己独特的属性(如subordinates)和方法(如manage()和addSubordinate())。
- 现在,我们可以创建一个Programmer类,也继承自Employee类:
public class Programmer extends Employee { private String programmingLanguage; public Programmer(String name, int age, double salary, String programmingLanguage) { super(name, age, salary); this.programmingLanguage = programmingLanguage; } public void code() { System.out.println("Programmer is coding in " + programmingLanguage); } // Other programmer-specific methods }
- 多态的应用:
多态允许我们将子类对象当作父类对象来处理。这意味着我们可以在不了解具体类型的情况下,使用父类引用来调用子类的方法。例如:
public static void main(String[] args) { Employee employee1 = new Manager("Alice", 30, 10000); Employee employee2 = new Programmer("Bob", 25, 8000, "Java"); employee1.work(); // 输出 "Employee is working..." employee2.work(); // 输出 "Employee is working..." // 由于多态,我们可以将Manager和Programmer对象当作Employee对象来处理 if (employee1 instanceof Manager) { Manager manager = (Manager) employee1; manager.manage(); // 输出 "Manager is managing..." } if (employee2 instanceof Programmer) { Programmer programmer = (Programmer) employee2; programmer.code(); // 输出 "Programmer is coding in Java" } }
在这个例子中,我们可以看到多态的优势。我们可以使用Employee类型的引用来调用Manager和Programmer类的方法,而无需关心它们的具体类型。这使得我们的代码更加灵活和可扩展。