簡體   English   中英

如何通過接口從實現接口的類調用方法?

[英]How to call a method from a class which implements an interface, through the interface?

我有以下界面:

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;
    }

在另一個類 - Building 中,我有一個HashMap<Office, IStaff> offices ,其中 Office 是一個普通類,它只保存辦公室的編號,並且有一個用於該編號的吸氣劑。

然后在另一個類 Company 中,我有一個ArrayList<Building> buildings ,它保存有關公司所有建築物的信息。 在這門課上,我需要了解工人的年齡,但我該怎么做? 到目前為止,我有一個這樣的循環來訪問地圖:

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

有沒有辦法做到這一點?

唯一真正的答案是:當您需要在只顯示您的界面的地方提供此類信息時,該信息需要位於界面上。

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

旁注:

  • 在類名中使用I作為“接口”......是不好的做法,或者至少:非常違反 Java 約定。
  • 你不需要在你的界面中有一個toString() 無論如何,您都可以從 Object 獲得一個。

(當然,有一些骯臟的技巧,比如在某處做一個instanceof檢查,然后轉換為具體類的類型。但正如所說:那是非常糟糕的做法)

使 IStaff 成為抽象類,然后調用該方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM