Class declaration in class

I have

1) basic interface,

2) several classes that implement this interface,

3) and the general class that I want to accept as a parameter, any of the implementing classes

I tried the following:

public class Foo extends Bar<? extends SomeInterface> { public Foo(List<? extends SomeInterface> someInterfaceList) { super(someInterfaceList); } ... } 

I get a No Wildcard Expected error. Elsewhere in my code, I have statements like List<? extends SomeInterface> List<? extends SomeInterface> and I am not getting any errors, so why am I having problems here? How can I fix this problem and get the desired results?

I tried searching for “No wildcards” and “wildcard in class declaration” to no avail. Thanks in advance!

+5
source share
2 answers

It looks like you want to declare a generic type argument that you specify elsewhere. Wildcards make sense only when the type is used only once, and when declaring a generic type parameter for a class, it makes no sense.

Try this instead:

 public class Foo<T extends SomeInterface> extends Bar<T> { public Foo(List<T> someInterfaceList) { super(someInterfaceList); } ... } 

Since your code was written, the user had nothing to specify the generic type argument for Bar<> , since Foo itself was not a generic type.

In addition, if it were possible, it would be possible for the general argument Bar<> differ from the general argument List<> - until both types implemented by SomeInterface would have a problem compiling with these definitions, but could You get a much more confusing error message later when you mistakenly assumed that both types should be the same.

So, declare a generic type once as a generic argument to the Foo class, and then use that type ( T in my example) elsewhere to refer to this type, instead of accepting some new generic type argument that might not belong to one type.

+6
source

I'm not quite sure what you are looking for, so it can help if you can provide a little more detail. Perhaps you can be a little more specific about how you plan to instantiate and use these objects?

Anyway, I think you can find something like this:

 import java.util.List; public class Foo<T extends SomeInterface> { public Foo(List<T> someInterfaceList) { for (T item : someInterfaceList) { // do something with each item } } } class Bar<T> {} interface SomeInterface<T> { T x(T y); } 

Or, alternatively, you can simply use the following for the constructor:

 public Foo(List someInterfaceList) { 

but you would not have an easy way to get the type T of the items in the list.

+1
source

Source: https://habr.com/ru/post/1201051/


All Articles