Krisi
Krisi

Reputation: 13

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

I have the following interface:

public interface IStaff {
    public StaffPosition getPosition();

    public String toString();
}

and the class:

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

In another class - Building, I have a HashMap<Office, IStaff> officeswhere Office is a normal class which only holds the number of the office and has a getter for that number.

And then in a yet another class Company I have an ArrayList<Building> buildings, which holds information about all the buildings of a company. In this class I need to get the age of a worker but how can I do that? So far I have a loop like this to get to the map:

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

Is there a way to do that?

Upvotes: 0

Views: 40

Answers (2)

GhostCat
GhostCat

Reputation: 140417

The only real answer is: when you need such an information in places where only your interface should show up, then that information needs to sit on the interface.

So your interface could have a method getAge(), or maybe getBirthday().

Side notes:

  • using I for "interface" in class names ... is bad practice, or at least: very much against java conventions.
  • you don't need to have a toString() in your interface. You get one from Object anyway.

(of course, there are dirty tricks, like doing an instanceof check somewhere, and then casting to the type of the concrete class. But as said: that is really bad practice)

Upvotes: 1

Fasde
Fasde

Reputation: 80

Make IStaff an abstract class and then call the method.

Upvotes: 0

Related Questions