import javax.swing.JOptionPane; // This is an example illustrating inheritance and ploymorphism using Java class Object public class Example5A { public Example5A() { String out = ""; Object A = new Object(); out += "A refers to an Object. A.toString() is: "; out += A.toString() + "\n"; // Since A refers to a Object object this will call // the Object toString() // out += A.length(); will not compile since A is an Object variable and // length() is not a member of Object A = new String("Sample String"); // A superClass varable can be assigned any of it's subclasses // So an Object variable can be assigned any class object out += "A now refers to a String. A.toString() is: "; out += A.toString() + "\n"; // Since A refers to a String object now this will call // the String toString(). This illustrates polymorphism // out += A.length(); will not compile since A is an Object variable and // length() is STILL not a member of Object int length = ((String)A).length(); // A superClass variable can be cast to any of it's subclasses // so an Object variabel can be cast to any class and // the compiler will not complain. Since A refers to a // String object here a runtime error will NOT occur A = 37; out += "A now refers to an Integer. A.toString() is: "; out += A.toString() + "\n"; // polymorphism again JOptionPane.showMessageDialog(null,out); length = ((String)A).length(); // An Object variable can be cast to any class // so the compiler will not complain. Since A refers to an // Integer object here a RUNTIME ERROR WILL occur } // end Example5A() public static void main(String[] args) { new Example5A(); } // end main } // end Example5A