So I have got 2 generic interfaces.
First interface is implemented like this.
public interface First<E>
{
void method(E e)
}
public class FirstImpl implements First<String>
{
void method(String s) { System.out.println(s); }
}
public class FirstImpl2 implements First<Double>
{
void method(Double d) { System.out.println(d); }
}
I need the second interface's (second interface is shown below) generic type to allow only the classes that are used when implementing the first interface, in our case String
and Double
. Is there any clean way to do this, something like
public interface Second <E, ? extends First<E>>
{
void method(E e);
}
public class SecondImpl <E> implements Second <E, ? extends First<E>>
{
void method(E e) { System.out.println(e); }
}
, so the in Second's generic E
would fit only String
and Double
and all classes that are used to implement First<E>
?
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.
A generic type class cannot extend the throwable class therefore, you cannot catch or throw these objects.
How can we restrict Generics to a super class of particular class? In MyListGeneric, Type T is defined as part of class declaration. Any Java Type can be used a type for this class. If we would want to restrict the types allowed for a Generic Type, we can use a Generic Restrictions.
Bounded Type Parameters There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.
Nope. You can not restrict the generic type of the Second in that sense. You can still provide an another type information independently. Say,
class XYZ implements First<Bar> { ... }
an another class may provide an another type information for the Second, like
class ZYX implements Second<Foo, SomeOtherType<Foo>> { ... }
assuming SomeOtherType implements/extends whatever from type First. If you want to bind those two interfaces on their generic type, you can use inheritance between the implementations:
interface First<T> {}
interface Second<T> {}
class Foo<E extends T> implements First<T> {}
class Bar<E extends T> extends Foo<E> implements Second<E> {}
Now, the type E, is associated with the type T, via E extends T.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With