Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested extends in generics

Tags:

java

generics

I have three classes:

class ClassR {}
class ClassA<T extends ClassR>{}    
class ClassB<E extends ClassA<T extends ClassR>> extends ClassA<T> {
    void foo(T param) {
    }

    void bar(E param) {
    }
}

The third class does not compile unless I change it to

class ClassB<E extends ClassA<T>, T extends ClassR> extends ClassA<T> {
    void foo(T bar) {
    }

    void bar(E param) {
    }
}

Is there a way to keep only E parameter I need to pass when creating ClassB, and T being inferred? For example, it would be convenient to use:

new ClassB<ClassA<ClassR>>()

instead of:

new ClassB<ClassA<ClassR>, ClassR>()
like image 951
Nutel Avatar asked Jul 10 '15 15:07

Nutel


People also ask

Is it possible to extend from a generic class?

We can add generic type parameters to class methods, static methods, and interfaces. Generic classes can be extended to create subclasses of them, which are also generic.

How do you declare a generic type in a class explain?

The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section. The type parameter section of a generic class can have one or more type parameters separated by commas.

What are generics in Java?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.


1 Answers

This even simpler approach might work for you:

class ClassR {}
class ClassA<T extends ClassR>{}    

class ClassB<T extends ClassR> extends ClassA<T> {
    void foo(T bar) {
    }

    void bar(ClassA<T> param) {
    }
}

And usage then bypasses any reference to ClassA to become:

class SubR extends ClassR {}

ClassB<SubR> obj = new ClassB<SubR>();
like image 199
Bohemian Avatar answered Oct 12 '22 22:10

Bohemian