Search code examples
javainterface

How to separate the logic in the implementation of a method whose signature is in two interfaces implemented by the class?


Question from interview:

How can I separate logic in method getString() of class ImplementationAB depending on the type of interface to which an instance of this class is assigned?

instanceof is not suitable for this task, it determines whether a class implements an interface:

interface A {
    public String getString();
}

interface B {
    public String getString();
}

class ImplementationAB implements A, B {
    
    @Override
    public String getString() {
        //TODO
    }
}

public class Main {
    public static void main(String[] args) {
        A a = new ImplementationAB();
        B b = new ImplementationAB();
       
        System.out.println(a instanceof B); //true
        System.out.println(b instanceof A); //true
        a.getString();
        b.getString();              
    }
}

Solution

  • Unfortunately that is not possible. At runtime, the information about which interface you used to instantiate the class is no longer available. Add the following lines to your code:

    System.out.println(a.getClass()); // ImplementationAB
    System.out.println(b.getClass()); // ImplementationAB
    

    Here you can see that only information about the interfaces is available, but only about the class.