University of Washington, CSE 142

Lab 9: Inheritance; Final Exam Practice

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

Basic lab instructions

Today's lab

Goals for today:

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

Critters (syntax)

import java.awt.*;

public class ClassName extends Critter {
    fields, constructors...

    public boolean eat() { ... }
    public Attack fight(String opponent) { ... }
    public Color getColor() { ... }
    public Direction getMove() { ... }
    public String toString() { ... }
}

Exercise : Skunk errors practice-it

The following critter ( icon Skunk.java ) is an attempt to make a critter that goes W, W, N and repeats, unless he eats food, in which case he will start going W, W, S. But the file contains errors. Download it and fix the errors so it compiles/runs properly. Test it in CritterMain and Practice-It.

public class Skunk extend Critter {
    private int moves;
    private boolean hungry;
    
    public void Skunk() {  // constructor
        hungry = false;
    }
    public static boolean eat() {
        hungry = true;
        return true;
    }
    public Direction getmoves() {
        moves++;
        if (moves >= 3) {
            moves = 0;
        }
        if (moves == 1 && moves == 2) {
            return Direction.WEST;
        } else if (hungry) {
            return Direction.NORTH;
        } else if (!hungry) {
            return Direction.SOUTH;
        }
    }
}

Exercise : Butterfly practice-it

Write a class Butterfly that extends the Critter class, along with its movement behavior. All unspecified aspects of Butterfly use the default behavior.

A Butterfly should be yellow in color. Its toString should alternate between being an x character and a - character each move.

A Butterfly flies upward in the following pattern: N, W, N, E, repeat.

Solve this program in jGRASP using the CritterMain simulator. Test it in Practice-it.

Final exam review

The CSE 142 final exam is usually very similar to the format of the practice exams. The following kinds of problems will be on your final exam:

Feel free to skip ahead to the types of problems on which you need the most practice.

Exercise : array simulation practice-it

Consider the following method:

public static void mystery(int[] list) {
    for (int i = 0; i < list.length; i++) {
        list[i] = i * list[i];
    }
}

In the left-hand column below are specific lists of integers. Indicate in the right-hand column what values would be stored in the list after method mystery executes if the integer list in the left-hand column is passed to it as a parameter.

{}
{}
{7}
{0}
{3, 2}
{0, 2}
{5, 4, 3}
{0, 4, 6}
{2, 4, 6, 8}
{0, 4, 12, 24}

Exercise : reference mystery practice-it

What four lines of output are produced by the following program?

public class ReferenceMystery {
    public static void main(String[] args) {
        int y = 1;
        int x = 3;
        int[] a = new int[4];
        mystery(a, y, x);                                             // 2 3 [0, 0, 17, 0][^0-9,]+
        System.out.println(x + " " + y + " " + Arrays.toString(a));   // 3 1 [0, 0, 17, 0][^0-9,]+
        x = y - 1;
        mystery(a, y, x);                                             // 1 0 [17, 0, 17, 0][^0-9,]+
        System.out.println(x + " " + y + " " + Arrays.toString(a));   // 0 1 [17, 0, 17, 0][^0-9,]+
    }

    public static void mystery(int[] a, int x, int y) {
        if (x < y) {
            x++;
            a[x] = 17;
        } else {
            a[y] = 17;
        }
        System.out.println(x + " " + y + " " + Arrays.toString(a));
    }
}

Exercise : inheritance mystery practice-it

Assume the following classes have been defined:

public class A extends B {
    public void method2() {
        System.out.println("a 2");
    }
}
public class D extends B {
    public void method1() {
        System.out.println("d 1");
    }
}
public class C {
    public String toString() {
        return "c";
    }

    public void method1() {
        System.out.println("c 1");
    }

    public void method2() {
        System.out.println("c 2");
    }
}
public class B extends C {
    public String toString() {
        return "b";
    }

    public void method2() {
        System.out.println("b 2");
    }
}

continued on the next slide...

Exercise - inheritance mystery

b
c 1
a 2
b
c 1
b 2
c
c 1
c 2
b
d 1
b 2

Consider the code below that uses these classes.
Write each line of its output in the boxes at right.

C[] elements = {new A(),
                new B(),
                new C(),
                new D()};
for (int i = 0; i < elements.length; i++) {
    System.out.println(elements[i]);
    elements[i].method1();
    elements[i].method2();
}

Exercise : inheritance mystery 2 practice-it

Assume the following classes have been defined:

public class Denny extends John {
    public void method1() {
        System.out.print("denny 1 ");
    }
    public String toString() {
        return "denny " + super.toString();
    }
}
public class Cass {
    public void method1() {
        System.out.print("cass 1 ");
    }
    public void method2() {
        System.out.print("cass 2 ");
    }
    public String toString() {
        return "cass";
    }
}
public class Michelle extends John {
    public void method1() {
        System.out.print("michelle 1 ");
    }
}
public class John extends Cass {
    public void method2() {
        method1();
        System.out.print("john 2 ");
    }
    public String toString() {
        return "john";
    }
}

continued on the next slide...

Exercise - inheritance mystery 2

cass 1
cass 2
cass
denny 1
denny 1 john 2
denny john
cass 1
cass 1 john 2
john
michelle 1
michelle 1 john 2
john

Consider the code below that uses these classes.
Write each line of its output in the boxes at right.

Cass[] elements = {new Cass(),
                   new Denny(),
                   new John(),
                   new Michelle()};
for (int i = 0; i < elements.length; i++) {
    elements[i].method1();
    System.out.println();
    elements[i].method2();
    System.out.println();
    System.out.println(elements[i]);
    System.out.println();
}

Exercise : isAllEven practice-it

Write a method called isAllEven that takes an array of integers as a parameter and that returns whether or not all of the values are even numbers (true for yes, false for no).

You should solve this problem in Practice-It!

Exercise : reverseLines practice-it

Write a method called reverseLines that takes a Scanner containing an input file as a parameter and that echoes the input file to System.out with each line of text reversed.

You should solve this problem in Practice-It!

Exercise : longestSortedSequence practice-it

Write a method called longestSortedSequence that accepts an array of integers as a parameter and that returns the length of the longest sorted (nondecreasing) sequence of integers in the array.

You should solve this problem in Practice-It!

Date class

Suppose you are given a class named Date with the following contents:

// A Date stores a month and day of the (non-leap) year.
public class Date {
    private int month;
    private int day;

    // constructs a new Date with the given month/day
    public Date(int m, int d)

    // returns the fields' values
    public int getMonth()
    public int getDay()

    public int daysInMonth()
    public void nextDay()
    public String toString()

    ...
}

Exercise : Date subtractWeeks practice-it

Exercise : Hyena

Write a class Hyena that extends the Critter class, along with its movement behavior. All unspecified aspects of Hyena use the default behavior.

A Hyena object moves in a rectangular pattern looking for food, walking NORTH, then EAST, then SOUTH, then WEST. Each time the hyena walks an entire rectangle, it starts the rectangle pattern over again but with a rectangle 1 step wider than before. The general pattern is as follows:

Solve this program in jGRASP using the CritterMain simulator.

Exercise : Hyena revisited practice-it

Modify your Hyena class from the previous problem to add eating behavior. If the hyena encounters food at any point during its movement pattern, it eats the food and starts the pattern over, lengthening the rectangular pattern by 1 in the process. For example:

Solve this program in jGRASP with CritterMain, then test it using the Practice-it link above.

Exercise : array simulation practice-it

Consider the following method:

public static void arrayMystery(int[] a) {
    for (int i = 1; i < a.length - 1; i++) {
        a[i] = a[i - 1] - a[i] + a[i + 1];
    }
}

In the left-hand column below are specific lists of integers. Indicate in the right-hand column what values would be stored in the list after method mystery executes if the integer list in the left-hand column is passed to it as a parameter.

{42, 42}
{42, 42}
{6, 2, 4}
{6, 8, 4}
{7, 7, 3, 8, 2}
{7, 3, 8, 2, 2}
{4, 2, 3, 1, 2, 5}
{4, 5, 3, 4, 7, 5}
{6, 0, -1, 3, 5, 0, -3}
{6, 5, 9, 11, 6, 3, -3}

Exercise : append practice-it

Write a method called append that accepts two integer arrays as parameters and that returns a new array that contains the result of appending the second array's values at the end of the first array.

You should solve this problem in Practice-It!

Exercise : Shark practice-it

Shark objects should alternate between moving to the north and south as follows: first move 1 step north, then 2 steps south, then 3 steps north, then 4 steps south, then 5 steps north, then 6 steps south, and so on, each time moving one farther than previously.

Solve this program in jGRASP with CritterMain, then test it using the Practice-it link above.

Exercise : array simulation practice-it

Consider the following method:

public static void arrayMystery(String[] a) {
    for (int i = 0; i < a.length; i++) {
        a[i] += a[a.length - 1 - i];
    }
}

In the left-hand column below are specific lists of strings. Indicate in the right-hand column what values would be stored in the list after method mystery executes if the string list in the left-hand column is passed to it as a parameter.

{"a", "b", "c"}
{"ac", "bb" ,"cac"}
{"a", "bb", "c", "dd"}
{"add", "bbc", "cbbc", "ddadd"}
{"z", "y", "142", "w", "xx"}
{"zxx", "yw", "142142", "wyw", "xxzxx"}

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 the book and try to solve them!