This sounds like a basic stuff and I cannot get it work.
Let's assume I need an application that stores all the workers in my company. They do different stuff and the price for their job depends on the specifics of the profession. For each worker I need a price.
What I do:
Create an interface of a Worker
public interface Worker {
int getPrice();
}
Create a class of LanguageTranslator who's salary depends on NumberOfLines of text which is translated. The class implements Worker. Of course, for other proffesions I will have other factors influencing the price.
public class LanguageTranslator implements Worker {
private int numberOfLines;
@Override
public int getPrice() {
return this.numberOfLines * 14;
}
public void setNumberOfLines(int numberOfLines) {
this.numberOfLines = numberOfLines;
}
}
And now, I want to store all the workers in a List, Map or whatever collection and have direct access to setNumberOfLines method.
public static void main(String[] args) {
List<Worker> workers = new ArrayList<Worker>();
Worker worker = new LanguageTranslator();
workers.add(worker);
//How to get to LanguageTranslator.setNumberOfLines() method?
}
}
If I go directly to the collection
workers.get(0).[only interface methods visible];
only interface methods are available. Is there any way to get to the specific LanguageTranslator methods?
I suppose this may be very bad design. Any keywords I could search for?
Thanks in advance.
You'll need to cast each object as you get it from the list. In the comments you mentioned that you'll have different professions that will later be added. Since you don't know which type to cast it as, you'll need to check.
Object object = workers.get(0);
if(object instanceof LanguageTranslator) {
LanguageTranslator lt = (LanguageTranslator) object;
lt.setNumberOfLines(7);
}
else if(object instanceof Accountant) {
Accountant acc = (Accountant) object;
acc.doSomething();
}
etc...
You have to understand that all instances that are of a LanguageTranslator type are also of a Worker type, but not all instances that are of a Worker type are also of a LanguageTranslator type. Therefore you can't call LanguageTranslator methods on all Worker instances.
You can cast instances of a Worker type to a LanguageTranslator type, but you must always check if that instance really is a of LanguageTranslator type first.
if(worker instanceof LanguageTranslator) {
((LanguageTranslator) worker).setNumberOfLines(1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With