Generic super class in java

2019-05-03 12:00发布

问题:

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 GenericView and HorizontalLayout and

public class MyView2 extends GenericView<VerticalLayout>

extends GenericView and VerticalLayout?

回答1:

The short answer - no. The type you extends must be an actual type, not a generic type parameter.



回答2:

It sounds like you want to accomplish multiple inheritance, inheriting from both a View and a Layout. This is not possible in Java. You can accomplish something similar with composition. If your GenericView must also provide the functionality given by AbstractLayout, then you can accomplish it like this:

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() {
        // ...
    }
}

After this, you can actually do this:

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

Hope this helps.



回答3:

Sadly this is not possible in Java. The main reason I can think of is the problem with Type Erasure - once that class is compiled it will no longer know what LAYOUTTYPE is.

What I think you're trying to achieve is a sort of multiple inheritance - so you can combine features from LAYOUTTYPE with those of GenericView. Multiple inheritance is - as you probably know - not possible in Java. However you can use multiple interfaces which for many cases will be sufficient. If you're using Java 8 you can even have default implementations for many functions in those interfaces (though only if it makes sense of course).