Generic superclass in java

Is it possible to create something like this in java

public abstract class GenericView<LAYOUTTYPE extends AbstractLayout> extends LAYOUTTYPE

so that

public class MyView extends GenericView<HorizontalLayout>

extends GenericViewand HorizontalLayoutand

public class MyView2 extends GenericView<VerticalLayout>

extends GenericViewand VerticalLayout?

+4
source share
4 answers

The short answer is no. The type you extendsmust be the actual type, not a typical type parameter.

+7
source

It looks like you want to do multiple inheritance, inheriting both from Viewand from Layout. This is not possible in Java. You can do something similar with composition. If your GenericViewshould also provide the functionality specified AbstractLayout, you can execute it as follows:

public interface Layout {
    // Layout functions
    public void doLayout();
}

public class GenericView<T extends AbstractLayout> implements Layout {
    private final T delegateLayout;

    // Construct with a Layout
    public GenericView(T delegateLayout) {
        this.delegateLayout = delegateLayout;
    }

    // Delegate Layout functions (Eclipse/IntelliJ can generate these for you):
    public void doLayout() {
        this.delegateLayout.doLayout();
    }

    // Other GenericView methods
}

public class VerticalLayout extends AbstractLayout {
    public void doLayout() {
        // ...
    }
}

:

new GenericView<VerticalLayout> (new VerticalLayout());

, .

+2

, Java. , , Type Erasure - , , LAYOUTTYPE.

, , , LAYOUTTYPE GenericView. - , , , Java. , . Java 8, default (, , ).

+1

"A class cannot inherit from its type parameter" (Source: IntelliJ IDEA).

0
source

All Articles