Re: Polymorphism in Java SE?
Stefan Ram wrote:
For teaching purposes, I'd like to know a Java-SE method
that returns an object whose class is only known at runtime
and can be shown to have at least two possibly values by
running a small program.
It would be best if this would be a static method that can
be called without any preparation.
[...]
Use Collections.unmodifiableList() on a List reference that
is made to refer to various kinds of Lists:
List list = new ArrayList();
Class c1 = Collections.unmodifiableList(list).getClass();
list = new LinkedList();
Class c2 = Collections.unmodifiableList(list).getClass();
list = Arrays.asList(argsOfMain);
Class c3 = Collections.unmodifiableList(list).getClass();
Maybe not compelling enough, because even though the List-ness
of list doesn't determine the class of the unmodifiable wrapper,
the actual nature of the object it refers to does. Maybe a more
direct example would be to use the parse() method of a NumberFormat
and show that sometimes it returns a Long and sometimes a Double.
A slightly different wrinkle: Catch an IOException and show
that different kinds of run-time failures generate different
subclasses: FileNotFoundException, EOFException, ...
--
Eric Sosman
esosman@ieee-dot-org.invalid