I was trying to do something like:
public class MyClass <A, B, C <A, B> > {
...
}
But Eclipse highlights "B," and says "unexpected , expected extends". What gives? Are nested generics not allowed?
To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters.
A Generic class can have muliple type parameters.
Using generics, primitive types can not be passed as type parameters. In the example given below, if we pass int primitive type to box class, then compiler will complain. To mitigate the same, we need to pass the Integer object instead of int primitive type.
Generics also provide type safety (ensuring that an operation is being performed on the right type of data before executing that operation). Hierarchical classifications are allowed by Inheritance. Superclass is a class that is inherited. The subclass is a class that does inherit.
It's because you haven't defined C
as a type that is itself typed with 2 type parameters.
Try something like this:
public class MyClass <A, B, C extends Map<A, B>> {
// This compiles
}
If your template parameters don't share share a class hierarchy, you can use an interface.
For example:
interface IConverter<TFrom, TTo>
{
TTo convert(TFrom from);
}
class IntToStringConverter implements IConverter<Integer, String>
{
public String convert(Integer from)
{
return "This is a string: " + from.toString();
}
}
class ConverterUser<TConverter extends IConverter<TFrom, TTo>, TFrom, TTo>
{
public ConverterUser()
{
}
private List<TConverter> _converter2;
private TConverter _converter;
public void replaceConverter(TConverter converter)
{
_converter = converter;
}
public TTo convert(TFrom from)
{
return _converter.convert(from);
}
}
class Test
{
public static void main(String[] args)
{
ConverterUser<IntToStringConverter, Integer, String> converterUser =
new ConverterUser<IntToStringConverter, Integer, String>();
converterUser.replaceConverter(new IntToStringConverter());
System.out.println(converterUser.convert(328));
}
}
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