Generic super class in java

回眸只為那壹抹淺笑 提交于 2019-12-05 10:41:39

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

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.

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

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