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
GenericView
HorizontalLayout
public class MyView2 extends GenericView<VerticalLayout>
extends GenericViewand VerticalLayout?
VerticalLayout
The short answer is no. The type you extendsmust be the actual type, not a typical type parameter.
extends
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:
View
Layout
AbstractLayout
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());
, .
, Java. , , Type Erasure - , , LAYOUTTYPE.
LAYOUTTYPE
, , , LAYOUTTYPE GenericView. - , , , Java. , . Java 8, default (, , ).
default
"A class cannot inherit from its type parameter" (Source: IntelliJ IDEA).