Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

migrating java classes to use generics [duplicate]

Tags:

java

generics

I have problem to use generics in one of my class. These are my classes:

public interface InterE<PK> {}

public interface Inter2<O extends ClassO, P extends ClassP> {}

public class ClassU<O extends ClassO, P extends ClassP> implements InterE<Long> {}

public class ClassP {}

public class ClassO {}

public class Class1<PK, T extends InterE<PK>> {
    public Class1 (Class<T> clazz) {}
}

public class Class2<O extends ClassO, P extends ClassP> extends Class1<Long, ClassU<O, P>> implements Inter2<O, P> {
    public Class2 () {
        //old constructor
        //super(ClassU.class);
        //new - here is problem
        super(ClassU<O, P>.class);
    }
}

If ClassU does not use generics, then old constructor in Class2 works fine, but I need to use generics in ClassU, so I have problem to call super constructor in Class2.

like image 249
podmak Avatar asked Jun 16 '15 06:06

podmak


People also ask

Can a class implement the same interface twice?

A class can implement multiple interfaces and many classes can implement the same interface. Final method can't be overridden. Thus, an abstract function can't be final.

Can a class implement different instantiations of the same generic interface Java?

This is not possible.

Can you instantiate a generic class?

Constructing an Instance of a Generic TypeYou cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the MakeGenericType method.

Can you implement twice Java?

Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).


1 Answers

Short story: change Class1 constructor parameter type - from Class<T> to Class<?>.

Why?

Class1 only needs T to extend InterE. Class2 declares ClassU to be this T argument. Since ClassU implements InterE, everything is OK for Class1.

Do you really need this <T> information in Class1 constructor? I think no:
1) T is already present in class declaration: Class1<PK, T extends InterE<PK>>, you can use it inside the class to generify code and make it compile-time safe:

 public class Class1<PK, T extends InterE<PK>> {
     Map<PK, T> map = new HashMap<>(); // can still use T, compile-time safe
 }

2) What can Class<T> do, that Class<?> can not do? - it can create newInstance() safe and do some more stuff, but you most likely won't use this possibility. Use still can operate with T, for example call T instance = (T) class.newInstance();, so you will not have any insuperable limitations.

like image 188
AdamSkywalker Avatar answered Sep 20 '22 01:09

AdamSkywalker