
import java.util.ArrayList;
import javax.swing.JOptionPane;

// This is an example illustrating inheritance and ploymorphism using Java class Object
public class Example4 {

    public static void main(String[] args) {
        Object oo = "37";
        System.out.println(oo.getClass());
        ArrayList<Object> objects = new ArrayList<Object>();
        objects.add("abc");
        objects.add(37);
        objects.add(new NumberTile());
        objects.add(new WordClass("while"));
        objects.add("def");
        String s = "def";
        boolean foundIt = false;
        for( Object x : objects ) {
            if( x.equals(s) ) {
                foundIt = true;
            }// end if
        }// end for
        JOptionPane.showMessageDialog(null, "Found it? " + foundIt);
        String s1 = "abcd";
        // A subclass variable cannot be assigned a superclass object. The following will not compile
        //s1 = new Object();
        // A subclass variable can be cast to it's superclass
        Object o = (Object)s1;
        String out = "";
        Object a = new Object();
        out += "a refers to an Object. a.toString() is: ";
        out += a.toString() + "\n"; // Since a refers to an 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 main
} // end Example4

