【问题标题】:How to call a method from a class which implements an interface, through the interface?如何通过接口从实现接口的类中调用方法?
【发布时间】:2019-12-08 19:00:06
【问题描述】:

我有如下界面:

public interface IStaff {
    public StaffPosition getPosition();

    public String toString();
}

和班级:

public class Worker implements IStaff {
    private String name = null;
    private String surname = null;
    private int age = 0;
    //StaffPosition is an enumeration class
    private StaffPosition position= null;
    public Worker (String name, String surname, int age, StaffPosition position){
        this.name = name;
        this.surname= surname;
        this.age= age;
        this.position= position;
    }
    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(this.name);
        buffer.append(" ");
        buffer.append(this.surname);
        return buffer.toString();
    }
    @Override
    public StaffPosition getPosition() {
        return this.position;
    }
    public int getAge(){
        return this.age;
    }

在另一个类 - 建筑物中,我有一个 HashMap<Office, IStaff> offices,其中 Office 是一个普通类,它只保存办公室的号码,并有一个用于该号码的吸气剂。

然后在另一个类公司中,我有一个ArrayList<Building> buildings,它包含有关公司所有建筑物的信息。在这门课上,我需要得到工人的年龄,但我该怎么做呢?到目前为止,我有一个这样的循环来到达地图:

for (Building building: buildings) {
    for (Map.Entry<Office, IStaff> office: building.offices.entrySet()) {
        //get the age of a worker
    }
}

有没有办法做到这一点?

【问题讨论】:

    标签: java class interface


    【解决方案1】:

    唯一真正的答案是:当您在只应显示您的界面的地方需要此类信息时,该信息需要位于界面上。

    所以你的界面可以有一个方法getAge(),或者getBirthday()

    旁注:

    • 在类名中使用 I 表示“接口”......是不好的做法,或者至少:非常违反 Java 约定。
    • 您的界面中不需要有toString()。无论如何,您都可以从 Object 获得一个。

    (当然,有一些肮脏的技巧,比如在某处进行instanceof 检查,然后强制转换到具体类的类型。但正如所说:这真的是不好的做法)

    【讨论】:

    • 是的,我正在考虑在界面中移动该方法,以防我无法访问它。谢谢!
    【解决方案2】:

    使 IStaff 成为一个抽象类,然后调用该方法。

    【讨论】:

    • 我需要它作为一个接口。有没有办法通过界面获取年龄?
    • 我不太习惯接口,更不习惯抽象类,但我不这么认为。据我所知,调用方法是继承的,但没有实现。但如果我错了,请有人纠正我。
    • 哦,好吧!还是谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-03-13
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多