I feel like I should know this, but can’t really explain it when asked.
I have a method:
public <T extends IByteConverter<T>> int write(T obj) throws IOException {
byte[] byteArray = obj.toByteArray();
raFile.write(byteArray);
//keeps track of size of what was written
return byteArray.length;
}
and my interface:
interface IByteConverter<T> {
public byte[] toByteArray();
public T fromByteArray(byte[] byteArray);
}
When I call obj.toByteArray(), How does my program know what to do? No where in my class do I actually implement the code in IByteConverter, but the program works just as expected. Is there a simple way to explain what is going on?
Let’s make the thing easier to understand with another example : you define an interface Fruit, which has a method
getColor(). The contract of this method is that it returns a color.Based on this contract, you define a class that takes an array of
Fruits, and counts the number of red ones.You don’t need any implementation for this method to compile, because you can be sure that the only thing that can be passed to this method is an array of objects, which are instances of a class that indeed implements the
Fruitinterface. In order for this method to be run, you’ll need to define at least one class that implements theFruitinterface (likeApplefor example), and to construct an array of objects of this class.That’s what polymorphism is all about: you can call a method of an object without knowing what its actual class is, provided it respects the contract of its interface.
Generics don’t make this different. Since
objis of typeT, and sinceTextendsIByteConverter, you can call thetoByteArray()method onobj.