Inheritance and Object Type Casting

Lab Overview:

In this lab, we will demonstrate how to use Object type-casting and inheritance using Java.

Instructions:

Here is a more in-depth example of inheritance with type-casting. Consider the following classes:

Create a class named Person, and write the code below.

public class Person {
   String         name;
   static int     lifeSpan = 60;
   static double  ageFactor = 1.0;

   public Person() {
       name = "";
   }
   public Person(String aName) {
       name = aName;
   }
   public String getName() { return name; }
   public void setName(String aName) { name = aName; }
   public String toString() {
       return("Hello, my name is " + name);
   }
   public String talk() {
       return("I have nothing to say.");
   }
   public String walk() {
       return("I have nowhere to go.");
   }
   public static double lifeSpan() {
       return(lifeSpan * ageFactor);
   }
}

Create a class named Boy, and write the code below.

Create a class named Girl, and write the code below.

Create a class named TestPeople, and write the code below

Output:

The lifespan() method did not work in the way expected. That is because for class methods, method look-ups occur at compile time. The lifeSpan() method in the Person class is used by both the Boy and Person classes. In this case, since the method is static and is declared in the Person class, the ageFactor from the Person class is used. However, the Girl class has its own lifeSpan() method, so the ageFactor within the Girl class is used in that case.

Last updated