Generic super class in java

独自空忆成欢 提交于 2019-12-07 05:47:43

问题


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).



来源:https://stackoverflow.com/questions/26400049/generic-super-class-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!