Building Java Programs, 3rd edition

Lab: Inheritance

Except where otherwise noted, the contents of this document are Copyright 2013 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges and Whitaker Brand

Lab goals

Goals for this problem set:

Inheritance (syntax)

public class ClassName extends SuperClass {
    ...
}
super.methodName(parameters);

Exercise : Car and Truck practice-it

public class Car {
   public void m1() {
      System.out.println("car 1");
   }

   public void m2() {
      System.out.println("car 2");
   }

   public String toString() {
      return "vroom";
   }
}
public class Truck extends Car {
   public void m1() {
      System.out.println("truck 1");
   }
}
Truck mycar = new Truck();
System.out.println(mycar);    // vroom
mycar.m1();                   // truck 1
mycar.m2();                   // car 2

Exercise : Car and Truck revisited practice-it

public class Car {
   public void m1() {
      System.out.println("car 1");
   }

   public void m2() {
      System.out.println("car 2");
   }

   public String toString() {
      return "vroom";
   }
}
public class Truck extends Car {
   public void m1() {
      System.out.println("truck 1");
   }
    
   public void m2() {
      super.m1();
   }
    
   public String toString() {
      return super.toString() + super.toString();
   }
}
Truck mycar = new Truck();
System.out.println(mycar);    // vroomvroom
mycar.m1();                   // truck 1
mycar.m2();                   // car 1

Exercise : MonsterTruck practice-it

MonsterTruck bigfoot = new MonsterTruck();
bigfoot.m1();                  // monster 1
bigfoot.m2();                  // truck 1 / car 1
System.out.println(bigfoot);   // monster vroomvroom

Employee class hierarchy

Exercise : Marketer practice-it

Exercise : Janitor practice-it

Exercise : HarvardLawyer practice-it