Reputation: 1132
I've been struggling with this for some time. I have an interface defined like this:
public interface SomeInterface {
String someMethod();
}
This will be implemented by a number of model classes, e.g.
public class SomeClass implements SomeInterace {
...
@Override
public String someMethod(){
...
}
}
Finally I have a 3rd class which needs to call the doSomething method, remember that I have multiple models that conform to SomeInterface. So I have the method defined as:
public class SomeUsefulClass {
public void doSomethingCool(Class<SomeInterface>aParam) {
//How do I specify aParam.someMethod(); A cast doesn't work
}
}
Upvotes: 1
Views: 73
Reputation: 1150
You can invoke the method the way you already show in your code.
aParam.someMethod();
What happens is that depending on which implementation has been passed at runtime to the method, then that will be class that will be invoked.
So for example if you have the following classes: Lamborghini,Porsche and Ferrari
And they all implement the Car class. You can pass in to a method a Car object which is an instance of Ferrari, then in the method the Ferrari code will be executed.
You do not need to define when you write the code which class will be invoked, at runtime the JVM can detect what object type came in.
This is a classic example of Polymorphism.
Upvotes: 0
Reputation: 1354
public void doSomethingCool(SomeInterface aParam) {
aParam.someMethod();
}
Upvotes: 6