// // contrived example of using inheritance and polymorphism // import java.util.* ; // // define a hierarchy of classes to hold integers, with each class // providing the following methods: // // printNum prints the number, plus "is prime" for primes // printSquare prints the number squared // printSquareRoot prints the number's square root if >= 0,, // an error message if < 0 // // // base class gives "default" behavior // class NumObj { int num ; NumObj(int n) { num = n ; } void printNum() { System.out.println(num) ; } void printSquare() { System.out.println(num + " squared is " + num*num) ; } void printSquareRoot() { System.out.println("unable to find square root of " + num) ; } } // // class for numbers >= 0 overrides some default behavior // class NonNegNumObj extends NumObj { NonNegNumObj(int n) { super(n) ; } // void printSquareRoot() { System.out.println("square root of " + num + " is " + Math.sqrt(num)) ; } } // // class for prime numbers (which are >= 0) overrides additional // default behavior // class PrimeNumObj extends NonNegNumObj { PrimeNumObj(int n) { super(n) ; } void printNum() { System.out.println(num + " is prime") ; } } // // main method showing use of NumObj and its subclasses // public class NumObjs { public static void main(String[] args) { // build a vector containing some NumObjs (of // different subtypes) Vector v = new Vector() ; v.addElement(new NumObj(-2)) ; v.addElement(new NonNegNumObj(0)) ; v.addElement(new PrimeNumObj(2)) ; v.addElement(new PrimeNumObj(3)) ; v.addElement(new NonNegNumObj(4)) ; // invoke NumObj methods on each element Enumeration e = v.elements() ; while (e.hasMoreElements()) { NumObj o = (NumObj) e.nextElement() ; o.printNum() ; o.printSquare() ; o.printSquareRoot() ; } } }