Minimizing code duplication when implementing multiple interfaces

I have one main interface and an abstract class that implements all the "deduced" methods (which can be written using only abstract methods):

public interface Main {
    public void main1(int x);
    public void main2();
}

public abstract class MainAbstract implements Main {
    public void main2() { main1(42); }
}

This functionality can be expanded in different directions:

public interface SubA extends Main {
     public void subA1(int x);
     public void subA2();
}

public interface SubB extends Main {
     public void subB1(int x);
     public void subB2();
}

Now I can have abstract classes SubAAbstractand SubBAbstractthat implement all the "deduced" methods (for example, main2in Main). The problem is that I can have specific implementations that want to implement both SubA , and SubB so, so I could use only one of the abstract classes. Actually, the problem is worse, because I have more than two sub-interfaces.

, Java, , .

[]

MainAbstract ( , Main),

public abstract class MainAbstract implements Main {

    public void main2() {
        main1(42);
    }

    public void subA1(int x) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void subA2() {
        subA1(4711);
    }

    public void subB1(int x) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void subB2() {
        subB1(-1);
    }

}

:

public class MainConcrete extends MainAbstract implements Main, SubA {

    public void main1(int x) {
        System.out.println("main " + x);
    }

    public void subA1(int x) {
        System.out.println("subA" + x);
    }

}

, , ( , - ), . , , , .

+3
3

, ..

0

, .

, .

:

+2

objweb asm bytecode-library , .

  public class ClassUtil {

public static Class<?> unifyClass(Class<?>...classes) {
    return ...;
}
}

And then

Class<?> subAllClass = unifyClass(SubA.class, SubB.class, ...);
0

All Articles