Implement common methods from an interface without clutter?

Is there a way to avoid the mess of adding all types to a class definition when implementing such an interface?

MyInterface.java

import java.util.List;
abstract class BaseA {}
abstract class BaseB {}
abstract class BaseC {}

interface MyInterface<T extends BaseA, U extends BaseB, V extends BaseC> {
    public void foo( List<? extends T> list );
    public void bar( List<? extends U> list );
    public void baz( List<? extends V> list );
} 

MyImplementation.java

/* Some concrete implementations of the abstract classes used in the interface */
class A extends BaseA{}
class B extends BaseB{}
class C extends BaseC{}

class MyImplementation implements MyInterface<A,B,C> {
    public void foo( List<? extends A> list){}
    public void bar( List<? extends B> list){}
    public void baz( List<? extends C> list){}
}

What I don't like about this is that the material that I think is method specific, like the type of parameters, mixes up with the class declaration. As in this case, where for each general method in the interface I have to add one formal type to the "bracket section".

Is there any other way to achieve the above (forcing the calling party of the implementation to use a specific subclass of the parameter class in the interface) without any “mess”?

, question.

+3
2

, , , , . ( ), :

abstract class PlayBase {}
interface MyInterface<T extends PlayBase> {
    public void playWith(List<T> list);
}   

... :

class A extends PlayBase {}
class MyImplementationA implements MyInterface<A> {
    public void playWith(List<? extends A> list){}
}

, ( ).

+1

:

interface MyInterface {
    public <T extends BaseA> void playWithA( List<? extends T> list );
    public <U extends BaseB> void playWithB( List<? extends U> list );
    public <V extends BaseC> void playWithC( List<? extends V> list );
}   
0

Source: https://habr.com/ru/post/1779758/


All Articles