首页 > 解决方案 > 无法使用动态多态性访问方法 [JAVA]

问题描述

我正在尝试解决以下问题在此处输入图像描述

我做了以下层次结构。

public abstract class Employee{

 private String name;
 private Integer id;
 protected Type type;

 Employee(){}

 Employee(String name,Integer id){
    this.name = name;
    this.type = type;           
 }

 abstract public void calculatePay();

 protected void benifits(){
    System.out.println("Basic Benifts");
 }

 public void printType(){
    System.out.println(this.type);
 }

}



public class Intern extends Employee{

 Intern(){
    super("default",123);
 }

 Intern(String name,Integer id){
    super(name,id);
    this.type = Type.Intern;
 }

 public void calculatePay(){
    System.out.println("Intern Pay");
 }

}

class Developer extends Employee{

 Developer(){
    super("default",123);
 }

 Developer(String name,Integer id){
    super(name,id);
    this.type = Type.Developer;
 }

 public void calculatePay(){
    System.out.println("Developer Pay");
 }

 protected void benifits(){
    super.benifits();
    System.out.println("Developer Benifits");
 }

}

class Manager extends Developer{

 public Manager(){
    super("default",123);
 }

 public Manager(String name,Integer id){
    super(name,id);
    this.type = Type.Manager;
 }

 public void calculatePay(){
    System.out.println("Manager Pay");
 }

 public void benifits(){
    super.benifits();
    System.out.println("Manger Benifits");
 }

 public void foo(){
    System.out.println("foo");
 }

}

驱动如下

class Driver{

    public static void main(String args[]){
        Employee manager = new Manager("Ali",1);
        manager.calculatePay();
        manager.benifits();     
        manager.printType();

        manager.foo();
    }

}

类型是一个枚举。现在的问题是我无法使用动态方法访问 foo() 方法。但是当我做静态多态时,Manager manager = new Manager()我可以访问它。

这种行为的具体原因是什么。我的设计正确吗?什么是更好的设计?我应该使用哪种设计模式?

标签: javainheritancepolymorphism

解决方案


不需要Type枚举,类本身(即Intern)代表员工类型。

与无法调用的问题相关的manager.foo()是,从特定类型的变量中,您只能调用在该类型(类)上声明的那些方法。

在您的情况下,当您声明时,Employee manager = new Manager("Ali", 1);您可以调用在上声明的方法Employee,在这种情况下,在类foo()上声明Manager


推荐阅读