University of Washington, CSE 142

Lab 8: Classes and Objects, Inheritance

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

lab document created by Marty Stepp, Stuart Reges, Whitaker Brand and Hélène Martin

Basic lab instructions

Today's lab

Goals for today:

Declaring a class (syntax)

public class ClassName {
    // fields
    fieldType fieldName;

    // methods
    public returnType methodName() {
        statements;
    }
}
A couple things look different than programs for past homeworks:

Exercise : Client code method call syntax practice-it

Suppose a method in the BankAccount class is defined as:

public double computeInterest(int rate)

If the client code has declared a BankAccount variable named acct, which of the following would be a valid call to the above method?

Exercise : PointCoordinates practice-it

What are the x- and y-coordinates of the Points referred to as p1, p2, and p3 after the following code executes? Give your answer as an x-y pair such as (0, 0). (Recall that Points and other objects use reference semantics.

Point p1 = new Point();
p1.x = 17;
p1.y = 9;
Point p2 = new Point();
p2.x = 4;
p2.y = -1;
Point p3 = p2;

p1.translate(3, 1);
p2.x = 50;
p3.translate(-4, 5);
p1:
(20, 10)
p2:
[^0-9,]+
(46, 4)
p3:
(46, 4)

Exercise : Point class errors

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import java.awt.*;
public class Point {
    int x;                                   // Each Point object has
    int y;                                   // an int x and y inside.

    public static void draw(Graphics g) {    // draws this point
        g.fillOval(p1.x, p1.y, 3, 3);
        g.drawString("(" + p1.x + ", " + p1.y + ")", p1.x, p1.y);
    }

    public void translate(int dx, int dy) {  // Shifts this point's x/y
        int x = x + dx;                      // by the given amounts.
        int y = y + dy;
    }

    public double distanceFromOrigin() {     // Returns this point's
        Point p = new Point();               // distance from (0, 0).
        double dist = Math.sqrt(p.x * p.x + p.y * p.y);
        return dist;
    }
}

The above Point class has 5 errors. Can you find them all?

Exercise - answer

  1. line 6: method header should not have the word static
  2. line 12: should not re-declare field x (delete word int)
  3. line 13: should not re-declare field y (delete word int)
  4. line 17: should not declare Point p
  5. line 18: should not use p. in front of the fields

Exercise - solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import java.awt.*;
public class Point {
    int x;                                   // Each Point object has
    int y;                                   // an int x and y inside.

    public void draw(Graphics g) {           // draws this point
        g.fillOval(x, y, 3, 3);
        g.drawString("(" + x + ", " + y + ")", x, y);
    }

    public void translate(int dx, int dy) {  // Shifts this point's x/y
        x = x + dx;                          // by the given amounts.
        y = y + dy;
    }

    public double distanceFromOrigin() {         // Returns this point's
        double dist = Math.sqrt(x * x + y * y);  // distance from (0, 0).
        return dist;
    }
}

Exercise : Printing objects practice-it

Point p1 = new Point();
...
System.out.println(p1);

The above println statement (the entire line) is equivalent to what?

Exercise : PointClient practice-it

Exercise : jGRASP Debugger

The debugger can help you learn how classes and objects work. In this exercise we will debug the Ch. 8 "Stock" Case Study example. This program tracks purchases of two stock investments. To download the example:

  1. Go to the class web page and click the "Textbook" link.
  2. Find the section labeled "Code Files" and click the "code files" link. Then click "ch08".
  3. Download and save the files Stock.java and StockMain.java. Right-click each file name and Save the Link in the same folder you use for lab work.
  4. Compile and run StockMain.java in jGRASP to see that it works.

continued on the next slide...

Exercise - jGRASP Debugger

continued on the next slide...

Exercise - jGRASP Debugger

continued on the next slide...

Exercise - jGRASP Debugger

Point and PointMain

Exercise : quadrant practice-it

Add the following method to the Point class:

public int quadrant()

Returns which quadrant of the x/y plane this Point object falls in. Quadrant 1 contains all points whose x and y values are both positive. Quadrant 2 contains all points with negative x but positive y. Quadrant 3 contains all points with negative x and y values. Quadrant 4 contains all points with positive x but negative y. If the point lies directly on the x and/or y axis, return 0.

(Test your code in Practice-It! or by running the PointMain program.)

Exercise : flip practice-it

Add the following method to the Point class:

public void flip()

Negates and swaps the x/y coordinates of the Point object. For example, if an object pt initially represents the point (5, -3), after a call of pt.flip(); , the object should represent (3, -5). If the same object initially represents the point (4, 17), after a call to pt.flip();, the object should represent (-17, -4).

Test your code in Practice-It! or by running the PointMain program.

Exercise : Point toString practice-it

Modify the toString method in the Point class. Make it return a string in the following format. For example, if a Point object stored in a variable pt represents the point (5, -17), return the string:

Point[x=5,y=-17]

If the client code were to call System.out.println(pt); , that text would be shown on the console.

(Test your code in Practice-It, or by running your PointClient or PointMain and printing a Point there.)

Exercise : manhattanDistance practice-it

Add the following method to the Point class:

public int manhattanDistance(Point other)

Returns the "Manhattan distance" between the current Point object and the given other Point object. The Manhattan distance refers to how far apart two places are if the person can only travel straight horizontally or vertically, as though driving on the streets of Manhattan. In our case, the Manhattan distance is the sum of the absolute values of the differences in their coordinates; in other words, the difference in x plus the difference in y between the points.

Click on the check-mark above to try out your solution in Practice-it! (Write just the new method, not the entire Point class.)

Exercise : Circle practice-it

Define a class named Circle. A Circle object stores a center point and a radius.

See the Practice-It link above for a full description of the class and the methods/constructors it should have. You can also test your class in Practice-It.

Rectangle class

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

// A Rectangle stores an (x, y) coordinate of its top/left corner, a width and height.
public class Rectangle {
    private int x;
    private int y;
    private int width;
    private int height;

    // constructs a new Rectangle with the given x,y, width, and height
    public Rectangle(int x, int y, int w, int h)

    // returns the fields' values
    public int getX()
    public int getY()
    public int getWidth()
    public int getHeight()

    // returns a string such as {(5,12), 4x8}
    public String toString()

    ...
}

Exercise : Rectangle union practice-it

Exercise : Rectangle contains practice-it

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

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.

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!