# University of Washington, CSE 142 (190)

## Lab 8: Classes

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:

• write our own new classes of objects
• declare fields, methods, and constructors
• understand the difference between class code and client code
• Where you see this icon, you can click it to check the problem in Practice-It! # Recall: Declaring a class (syntax)

```public class class name {
// fields
field type field name;

// methods
public return type method name() {
statements;
}
}
```
A couple things look different than programs for past homeworks:
• no `main` method. It won't be run like a client program.
• methods don't have the `static` keyword in the header.
• variables declared outside of any method (fields) are visible in every method.

# Exercise : Class and client code

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 What are the x- and y-coordinates of the `Point`s 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 `Point`s 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`: `[^0-9,]+` `(20, 10)` `p2`: `[^0-9,]+` `(46, 4)` `p3`: `[^0-9,]+` `(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?

1. line 6: method header should not have the word `static`
2. line 12-13: should not re-declare fields `x` and `y` (delete word `int`)
3. lines 17-18: should not declare `Point p` nor use `p.` in front of any 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

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

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

# BankAccount class

• The next exercise refers to the following `BankAccount` class (see next slide):
```// Each BankAccount object represents one user's account
// information including name and balance of money.

public class BankAccount {
String name;
double balance;

public void deposit(double amount) {
balance = balance + amount;
}

public void withdraw(double amount) {
balance = balance - amount;
}
}
```

# Exercise : BankAccount transactionFee • Download the following file BankAccount.java and open it with jGrasp.
• Add a `double` field named `transactionFee` that represents an amount of money to deduct every time the user withdraws money. The default value is `\$0.00`, but the client can change the value. Deduct the transaction fee money during every `withdraw` call (but not from deposits).
• Make sure that the balance cannot go negative during a withdrawal. If the withdrawal (amount plus transaction fee) would cause it to become negative, don't modify the `balance` value at all.
• Test your solution to this problem in Practice-It.

# `Point` and `PointMain`

• Download the following file PointMain.java to your machine and open it with jGrasp.
• Now edit `Point.java` and add two methods to the `Point` class as described on the next two slides. The `PointMain` program calls these methods; you can use it to test your code.

# Exercise : `quadrant` 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 by running the `PointMain` program.)

# Exercise : `flip` 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 the object initially represents the point (5, -3), after a call to `flip`, the object should represent (3, -5). If the object initially represents the point (4, 17), after a call to `flip`, the object should represent (-17, -4).

(Test your code by running the `PointMain` program. You will need to un-comment the `flip` testing code.)

# Exercise : `Point``toString`

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 `punkt` represents the point (5, -17), return the string:

```Point[x=5,y=-17]
```

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

(Test your code by running your `PointClient` or `PointMain` and printing a `Point` there.)

# Exercise : `BankAccount``toString`

Add a `toString` method to the `BankAccount` class. Your method should return a string that contains the account's name and balance separated by a comma and space. For example, if an account object named `benben` has the name `"Benson"` and a balance of 17.25, `benben.toString()` should return:

```Benson, \$17.25
```

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

(Test your code by writing a short client program that constructs and initializes an account, then prints it.)

# Exercise : `manhattanDistance` 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! (For this problem, write just the new method, not the entire `Point` class.)

# Exercise : `TimeSpan` Define a class named `TimeSpan`. A `TimeSpan` object stores a span of time in hours and minutes (for example, the time span between 8:00am and 10:30am is 2 hours, 30 minutes). The minutes should always be reported as being in the range of 0 to 59. That means that you may have to "carry" 60 minutes into a full hour.

To solve this problem, you will need to peek at the upcoming Wednesday lecture slides to learn the syntax for a constructor.

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.

# 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 8 and try to solve them!