import javax.swing.JOptionPane; // This is an example illustrating inheritance and ploymorphism class SuperClass { int x; public SuperClass(int x) { this.x = x; } String method1() { return "method1 in SuperClass\n"; } // end method1 String method2() { return "method2 in SuperClass\n"; } // end method2 } // end SuperClass class SubClass extends SuperClass { int y; public SubClass(int x,int y) { super(x); this.y = y; } String method2() { return "method2 in SubClass\n"; } // end method2 String method3() { return super.method2() + "method3 in SubClass\n"; } // end method3 } // end SubClass public class SuperClassSubClassExample { public static void main(String[] args) { String out = ""; SuperClass a = new SuperClass(37); out += a.method1(); out += a.method2(); // Since a refers to a SuperClass object this will call // the SuperClass method2 // out += a.method3(); will not compile since a is a SuperClass variable and // method3() is not a member of SuperClass JOptionPane.showMessageDialog(null, out); out = ""; a = new SubClass(37,73); // a superClass varable can be assigned any of it's subclasses out += a.method1(); out += a.method2(); // Since a refers to a SubClass object now this will call // the SubClass method2. This illustrates polymorphism // out += a.method3(); will not compile since a is a SuperClass variable and // method3() is STILL not a member of the SuperClass out += ((SubClass) a).method3(); // a SuperClass variable can be cast to any of it's subclasses // so the compiler will not complain. Since a refers to a // SubClass object here a runtime error will NOT occur JOptionPane.showMessageDialog(null, out); a = new SuperClass(111); //out += ((SubClass)a).method3(); // a SuperClass variable can be cast to any of it's subclasses // so the compiler will not complain. Since a refers to a // SuperClass object here a RUNTIME ERROR WILL occur SubClass b = new SubClass(111,222); JOptionPane.showMessageDialog(null, ((SuperClass) b).method2()); } // end main } // end Example 3