0

I have defined an interface like this:

public interface InterfaceA {
      String getMyString();
}

And I have two classes that implement the interface:

public class MyClassA implements InterfaceA {
     @Override
     public String getMyString(){
          return "A";         
     }
}

public class MyClassB implements InterfaceA {
     @Override
     public String getMyString(){
          return "B";         
     }
}

What I am trying to do is to create a method that accepts an object that implements InterfaceA as an argument and call its getMyString method. Here is some pseudo code that illustrates what I'm trying to accomplish:

public String getStringTest(T implements InterfaceA){
     return T.getMyString;         
}

3 Answers 3

6
public String getStringTest(InterfaceA myvalue){
   return myvalue.getMyString();         
}
Sign up to request clarification or add additional context in comments.

Comments

4

You can just specify the interface as a type directly. This means that any object from a class that implements this interface can be passed as an argument:

public String getStringTest(InterfaceA t){
     return t.getMyString();         
}

Comments

0

It's called a wrapper and can result in a decorator or adapter pattern.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.