Search code examples
javainheritancemethodsoverriding

Inherit override-equivalent as different methods


Several methods from interface, super class or new method are override equivalent. I need to make different realization for each. Example:


public interface A {
    int f();
}
public interface B {
    int f();
}
public class C implements A, B {
    // ???
}

C c = new C();
// return values doesn't matter
c.f(); // must print "C"
((A)c).f(); // must print "A"
((B)c).f(); // must print "B"

In C# it would be

// "print" prints first argument to the console
public class C : A, B {
    public int f() { print("C"); }
    public int A.f() { print("A"); }
    public int B.f() { print("B"); }
}

When created function int f(), all override equivalent methods were same.


Solution

  • As a continuation of my comment, I would like to include a code sample as well here. Again it is not directly possible in Java. But as a workaround, quote: "...use a workaround by creating wrapper classes for each interface and then delegating the method call to these wrapper classes."

    Here is the code:

    interface A {
        void f();
    }
    
    interface B {
        void f();
    }
    
    class WrapperA implements A {
        private final C c;
    
        public WrapperA(C c) {
            this.c = c;
        }
    
        @Override
        public void f() {
            System.out.println("A");
            c.f();
        }
    }
    
    class WrapperB implements B {
        private final C c;
    
        public WrapperB(C c) {
            this.c = c;
        }
    
        @Override
        public void f() {
            System.out.println("B");
            c.f();
        }
    }
    
    class C implements A, B {
        @Override
        public void f() {
            System.out.println("C");
        }
    
        public static A asA(C c) {
            return new WrapperA(c);
        }
    
        public static B asB(C c) {
            return new WrapperB(c);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            C c = new C();
            c.f(); // prints "C"
    
            A a = C.asA(c);
            a.f(); // prints "A" and "C"
    
            B b = C.asB(c);
            b.f(); // prints "B" and "C"
        }
    }