Jeslie C. answered 09/14/14
Tutor
3
(2)
Experienced Computer Science tutor - computers can be fun and easy!
A polymorphic variable is simply a variable capable of taking on instances of differing types. In Java the ultimate type (class) is Object, which every other class is a subclass of. The simplest example would be to consider the toString() method defined in Object. Nothing special. But not consider that when you write ...
println(x.toString());
... the value printed for "x" depends on the class hierarchy and which classes (Object > A > B > C) have toString() defined. If "x" comes from class C, then its toString() will control the String used for output. If there is no such method defined, then B will control, etc., all the way down to the Object.toString() method if there is nothing else.
What we are seeing here is the effect of inheritance (used to determine which toString() method to invoke) and that the behavior of the code, while consistent at one level (we will print out text that represents "x" in some way), the actual definition of what to do with "x" in this case depends on its type.
BTW, we'd normally code "println(x);" for the above code. The java.io.PrintStream.println() method is designed to apply the toString() method to whatever Object it receives. The println() method is coded simply to apply the method -- it doesn't know what the effect will be other than it should be returning a String which can then be output.