Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic super class 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 GenericView and HorizontalLayout and

public class MyView2 extends GenericView<VerticalLayout>

extends GenericView and VerticalLayout?

like image 614
vralfy Avatar asked Oct 16 '14 08:10

vralfy


People also ask

What are generic classes in Java?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

What is the super class of Java?

A: The Object class, which is stored in the java. lang package, is the ultimate superclass of all Java classes (except for Object ). Also, arrays extend Object .

What is <? Super T in Java?

super T denotes an unknown type that is a supertype of T (or T itself; remember that the supertype relation is reflexive). It is the dual of the bounded wildcards we've been using, where we use ? extends T to denote an unknown type that is a subtype of T .

What is difference between extends and super in generics?

extends Number> represents a list of Number or its sub-types such as Integer and Double. Lower Bounded Wildcards: List<? super Integer> represents a list of Integer or its super-types Number and Object.


2 Answers

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

like image 80
Mureinik Avatar answered Sep 19 '22 22:09

Mureinik


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.

like image 41
jhkuperus Avatar answered Sep 20 '22 22:09

jhkuperus