Building Java Programs

Lab 9: Inheritance

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

lab document created by Whitaker Brand and Marty Stepp

Today's lab

Goals for today:

Recall: Inheritance (syntax)

public class class name 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

Exercise : Janitor

If you finish them all...

If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook.

You can view an exercise, type a solution, and submit it to see if you have solved it correctly.

Choose some problems from Chapter 9 or Section 9 or the Practice Final Exams and try to solve them!