next up previous contents
Next: Inheritance 6: Method Lookup Up: Java Notes Previous: Inheritance 4: Protected

Inheritance 5: Method Call


/**
 *  This code is from the book:
 *  Winder, R and Roberts, G (1998)
 *  Developing Java Software</em>
 *  John Wiley & Sons.
 *  It is copyright (c) 1997 Russel Winder
 *  and Graham Roberts.
 */

class Superclass{
  private static String name = "Superclass";

  public void test(int i){
    System.out.println("Superclass test(int): " + i);
  }

  public void test(double i){
    System.out.println("Superclass test(double): " + 
                       i);
  }

  public String getName(){
    return name;
  }
}

class Subclass extends Superclass{
  private static String name = "Subclass";

  public void test(float i){
    System.out.println("Subclass test(float): " + i);
  }

  public void test(int i){
    System.out.println("Subclass test(int): " + i);
  }

  public String getName(){
    return name;
  }
}

class l1Inherit5{//Call1
  public static void main(String[] args){
    Superclass[] objs = new Superclass[5];
    objs[0] = new Superclass();
    objs[1] = new Subclass();
    objs[2] = new Superclass();
    objs[3] = new Subclass();
    objs[4] = new Subclass();

    for (int i = 0; i < 5; i++){
      System.out.println(objs[i].getName());
      objs[i].test(1);
      objs[i].test(1.0F);
    }

    ((Subclass)objs[1]).test(1.0F);
  }
}
/******** sample compilation & run *******
# javac l1Inherit5.java 
# java l1Inherit5
Superclass
Superclass test(int): 1
Superclass test(double): 1.0
Subclass
Subclass test(int): 1
Superclass test(double): 1.0
Superclass
Superclass test(int): 1
Superclass test(double): 1.0
Subclass
Subclass test(int): 1
Superclass test(double): 1.0
Subclass
Subclass test(int): 1
Superclass test(double): 1.0
Subclass test(float): 1.0
# 
******************************************/



Ananda Amatya
9/15/1999