Imagine code like this:
public class Value<T> {
private T value;
public Value(T value) {
this.value = value;
}
public int size() {
return sizeOf(value);
}
private int sizeOf(int value) {
return Integer.BYTES;
}
private int sizeOf(String value) {
return value.length() * Character.BYTES;
}
}
and somewhere (e.g. main
)
Value<String> value = new Value<String>("hello");
The problem is that the code will not compile, because I haven't implemented sizeOf(T value)
, but I don't understand why would the compiler complain --- it sees that I only use it with <T=String>
. And if I implement the generic sizeOf(T value)
, it will take precedence (as explained here Java generics (template) specialization possible (overriding template types with specific types) )
Note that the solution proposed there (having a StringValue
subclass) doesn't really apply in my case, because I already have some subclasses which I am using, so I would need to create lots of extra classes (times by types)
But I would prefer something much more straight-forward, such as this