CIS 121 Laboratory February 3, 2000


Examining Inheritance


In the c:\java subdirectory, create the following files.

One.java
public class One {
   protected int number;

   public One() {
      number = 0;
   }

   public int f() {
      return 0;
   }

   public int g() {
      return 1;
   }

   public static void main (String[] args) {
      System.out.println("One");
   }
}
Two.java
public class Two extends One {
   int num;

   public Two() {
      num = 1;
   }

   public int g() {
      return 2;
   }

   public int h() {
      return 3;
   }

   public static void main (String[] args) {
      System.out.println("Two");
   }
}
Three.java
public class Three extends Two {
   int num;

   public Three() {
      num=2;
   }

   public int f() {
      return 4;
   }

   public int h() {
      return 5;
   }

   public static void main (String[] args) {
      System.out.println("Three");
   }
}
Four.java
public class Four {

   public static void main (String[] args) {
      One myOne = new One();
      Two myTwo = new Two();
      Three myThree = new Three();

      System.out.println(myOne.f());
      System.out.println(myTwo.f());
      System.out.println(myThree.f());

      System.out.println(myTwo.h());
      System.out.println(myThree.h());
      System.out.println(myThree.g());

      System.out.println(myOne.g());
      System.out.println(myTwo.g());
      System.out.println(myThree.g());
   }

}
The rule regarding method calls and inheritance is that if a method is called, the hierarchy of classes is searched until the Object class is reached. The first defined body of the method which is found is executed.

Before compiling and executing Four.java, examine the code and determine what the output of Four will be. Then compile and execute Four.java to check your answers.