Re: Polymorphism in Java SE?
Stefan Ram wrote:
....
A near miss is the field ?System.in?, which indeed contains an
object of a proper /subtype/ of the field's type. So it is
somewhat polymorphic. You do not know the actual type until
run-time. It is only boring insofar as it is always the same
subtype.
....
Huh? Why do you say it is always the same subtype?
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class SystemDotInClasses {
public static void main(String[] args) throws IOException {
System.out.println("Initial class: "
+ System.in.getClass().getName());
String someData = "xyzzy";
InputStream someStream = new ByteArrayInputStream(
someData.getBytes());
System.setIn(someStream);
System.out.println("Second class: "
+ System.in.getClass().getName());
int firstByte = System.in.read();
if (firstByte == -1) {
System.out.println("Empty input");
} else {
System.out.println("First byte of input: "
+ (char) firstByte);
}
ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(outBytes);
out.writeDouble(Math.PI);
someStream = new DataInputStream(
new ByteArrayInputStream(outBytes.toByteArray()));
System.setIn(someStream);
System.out.println("Third class: "
+ System.in.getClass().getName());
double d = ((DataInputStream) System.in).readDouble();
System.out.println("Read from data stream " + d);
}
}
Patricia