Search code examples
javaoopdesign-patternsinterface

Two Interface with Same Method Name - Implementation of Methods


Suppose I have two interfaces:

interface IOne {

    public void method();

}

and

interface ITwo {

    public void method();

}

A concrete class implements both of the interfaces:

public class A implements IOne, ITwo {

    public void method(){
       //some implementation
    }
}

My questions are:

  1. Does the single implementation of method() suffice for both interfaces IOne and ITwo?
  2. If the answer of 1 is yes, is there any way to get both the methods in a single class? In this case it is not necessary we have to implement both interfaces in a single class.

Solution

  • For 1, the answer is yes. It's enough to provide one implementation for the method in the class for both interfaces to be automatically implemented.

    For 2, if you need to have both methods, then your class should not implement both interfaces. However, there's a trick you can use:

    interface IOne {
    
        void method();
    }
    
    interface ITwo {
    
        void method();
    }
    
    public class A
        implements IOne, ITwo {
    
        // Anonymous inner class that implements only IOne
        private final IOne one = new IOne() {
    
            @Override
            public void method() {
                System.out.println("IOne");
            }
        };
    
        // Anonymous inner class that implements only ITwo
        private final ITwo two = new ITwo() {
    
            @Override
            public void method() {
                System.out.println("ITwo");
            }
        };
    
        @Override
        public void method() {
            System.out.println("A");
        }
    
        // Method that delegates to IOne
        public void methodIOne() {
            this.one.method();
        }
    
        // Method that delegates to ITwo
        public void methodITwo() {
            this.two.method();
        }
    }
    

    Testing code:

    A a = new A();
    a.method(); // A
    a.methodIOne(); // IOne
    a.methodITwo(); // ITwo
    

    Class A doesn't need to implement both interfaces. In that case, just don't implement method() on A and keep only the anonymous inner classes.