Requirement: method read() in an interface IReader needs to accept a single argument but of various types
read(Book b) to be implemented by one concrete class BookReader
read(Score s) to be implemented by another concrete class ScoreReader
Suppose we want to unify the 2 read() methods into one unified method, so a “client” can get an instance of Reader and simply pass in either a book or a score. C# probably has language support for this, but in Java …
Solution 1: use Object argument
Solution 2: declare
read(T content, Class argumentClass);
BookReader.java implements
read(T content, Class argumentClass){
if (content instanceof Book){….
}
Paradoxically IDE may warn you that argumentClass is an unused variable inside the method. However Compiler use it to enforce type safety —
myReader.read(someBook, Integer.class);// won’t compile. Book.class required