Re: Polymorphism in Java SE?
ram@zedat.fu-berlin.de (Stefan Ram) writes:
For teaching purposes, I'd like to know a Java-SE method
that returns an object whose class is only known at runtime
Thanks for the answers so far!
Why do I not write a custom method or class for this?
I have this idea that teaching should go from the simple
things to more advanced things. To me, /using/ objects of
JAVA-SE classes is more simple than /declaring/ custom classes
(eating is more simple than designing a dish and cooking it).
Therefore, when I introduce objects and their properties,
I have not yet introduced class or non-static method
declarations: Most statements still go into the body of
the static ?main? method.
So, at this point, I would like to show how to /use/
polymorphic designs, but not yet how to create a new
design.
?DriverManager.getConnection()? might be of no use when used
in isolation and a full JDBC client might be too large at this
point.
To use the parse() method of a NumberFormat (Eric)
http://download.java.net/jdk7/docs/api/java/text/NumberFormat.html#parse(java.lang.String,%20java.text.ParsePosition)
, is very close to what I was looking for.
I will also look into catching an IOException,
Calendar.getInstance(), java.lang.Class.forName and
newInstance and other suggestions.
One example I already use, but which looks somewhat contrived
and not like the solution of any real problem is:
( Math.random() > .5 ? System.out : "example" ).hashCode()
This is simple: No containers, no declarations, just
polymorphism. There is an expression for an object whose
type is only known at run time and a verb ?hashCode?, which
indeed has two completely different implementations in
both cases. This is good so far.
The problem is: This example makes no real sense: One can not
imagine that one really needs this specific expression to
solve any problem. So I am looking for something as simple and
polymorphic as this but with more sense. Possibly I can use
the abovementioned ?parse? verb for this.