1

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
 }
}
Guillaume
19k8 gold badges56 silver badges76 bronze badges
asked Dec 2, 2014 at 21:11
0

2 Answers 2

6
public void doSomethingCool(SomeInterface aParam) {
 aParam.someMethod(); 
}
answered Dec 2, 2014 at 21:14
Sign up to request clarification or add additional context in comments.

Comments

0

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.

answered Dec 2, 2014 at 21:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.