Lab goals

Goals for this problem set:

• write our own new classes of objects
• declare fields, methods, and constructors
• understand the difference between class code and client code

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:
• 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 1: Client code method call syntax

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 2: 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`: `(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?

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 4: Printing objects

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

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

Exercise 5: PointClient

• The `PointClient` program is supposed to construct two `Point` objects, translate each, and then print their coordinates. Finish the program so that it runs properly. (You don't need to modify `Point.java`.)

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. Find the section labeled "Code Files" and click the "code files" link. Then click "ch08".
2. 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.
3. Compile and run `StockMain.java` in jGRASP to see that it works.

continued on the next slide...

Exercise - jGRASP Debugger

• Set a stop on the `System.out.print` on line 53, and debug the program.
• Type the user input to recreate the following partial log:
```First stock's symbol: AMZN
How many purchases did you make? 2
1: How many shares, at what price per share? 50 35.06
2: How many shares, at what price per share? 25 38.52
```
• At this point, what are the values of the fields in the `currentStock` object?
(Ask a TA if you need help.)  `totalShares` `75` `totalCost` `2716.0`

continued on the next slide...

Exercise - jGRASP Debugger

• Now let's debug inside one of the `Stock` object's methods. Your program should still be stopped. Set a new stop at the `return` on line 29 of `Stock.java`.
• Resume your program . It will prompt for today's price per share. Enter 37.29 . If you did it properly, the program should now call `getProfit` on the `Stock` and hit your stop point.
```What is today's price per share? 37.29
```
• What are the values of the object (`this`) 's fields, and the variable `marketValue` ?  `symbol` `"AMZN"` `totalShares` `75` `totalCost` `2716.0`

 `marketValue` `2796.75`

continued on the next slide...

Exercise - jGRASP Debugger

• Now let's watch the total shares and cost of a stock change with each purchase. Remove your existing stop points and set a new stop somewhere in the `for` loop on lines 42-50 of `StockMain`, and Resume .
• Type the user input to continue recreating the following partial log:
```Second stock's symbol: INTC
How many purchases did you make? 3
1: How many shares, at what price per share? 15 16.55
2: How many shares, at what price per share? 10 18.09
3: How many shares, at what price per share? 20 17.05
What is today's price per share? 17.82
```
• After each call of `purchase`, what are the field values of `currentStock`?
field after 1st purchase after 2nd after 3rd
`totalShares` 15 25 45
`totalCost` 248.25 429.15 770.15

BankAccount class

• The next exercise refers to the following BankAccount class (download it and open it in jGRASP).
```// 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 7: BankAccount transactionFee

• Add a `double` field to the `BankAccount` class 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.

`Point` and `PointMain`

• Now edit `Point.java` and add two methods to the `Point` class as described on the next two slides.

Exercise 8: `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.

Exercise 9: `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 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).

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

```java.awt.Point[x=5,y=-17]
```

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

Exercise 11: `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.

Exercise 12: `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.

Exercise 13: `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 may want to refer to the lecture slides about the syntax for constructors.

Exercise 14: `Circle`

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.

Exercise : Point class errors 2

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ``` ```public class Point { int x; // Each Point object has int y; // an int x and y inside. public void Point(int initX, int initY) { // Constructor initX = x; initY = y; } public static double distanceFromOrigin() { // Returns this point's int x; // distance from (0, 0). int y; double dist = Math.sqrt(x*x + y*y); return dist; } 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; } } ```

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

1. line 5: constructor header should not have the word `void`
2. line 6-7: the assignment statements are backwards; reverse left/right sides of each
3. line 10: method header should not have the word `static`
4. line 11-12: should not re-declare fields `x` and `y`
5. lines 18-19: should not re-declare fields `x` and `y` (remove word `int`)

Exercise - solution

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ``` /td> ```public class Point { int x; int y; public Point(int initX, int initY) { x = initX; y = initY; } public double distanceFromOrigin() { double dist = Math.sqrt(x*x + y*y); return dist; } public void translate(int dx, int dy) { x = x + dx; y = y + dy; } } ```

ClockTime class

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

```// A ClockTime object represents an hour:minute time during
// the day or night, such as 10:45 AM or 6:27 PM.
public class ClockTime {
private int hour;
private int minute;
private String amPm;

// Constructs a new time for the given hour/minute
public ClockTime(int h, int m, String ap)

// returns the field values
public int getHour()
public int getMinute()
public String getAmPm()

// returns a String for this time; for example, "6:27 PM"
public String toString()

...
}
```

• Write an instance method `advance` that will be placed inside the `ClockTime` class. The method accepts a number of minutes as its parameter and moves your object forward in time by that amount of minutes. The minutes passed could be any non-negative number, even a large number such as 500 or 1000000. If necessary, your object might wrap into the next hour or day, or it might wrap from the morning ("AM") to the evening ("PM") or vice versa. (A ClockTime object doesn't care about what day it is; if you advance by 1 minute from 11:59 PM, it becomes 12:00 AM.)
• For example, the following calls would produce the following results:
```ClockTime time = new ClockTime(6, 27, "PM");
time.advance(1440);    //  1:11 AM  (1 day later)
time.advance(21075);   //  4:26 PM  (2 weeks later)
```
• Test your solution to this problem in Practice-It.

Exercise 17: ClockTime isWorkTime

• Write an instance method `isWorkTime` that will be placed inside the `ClockTime` class. The method returns `true` if the object is a time during the "work day" from 9:00 AM - 5:00 PM inclusive; otherwise `false`.
• The following objects would return the following results if the method were called:
```ClockTime t0 = new ClockTime(12, 45, "AM");   // false
ClockTime t1 = new ClockTime( 6, 02, "AM");   // false
ClockTime t2 = new ClockTime( 8, 59, "AM");   // false
ClockTime t3 = new ClockTime( 9, 00, "AM");   // true
ClockTime t4 = new ClockTime(11, 38, "AM");   // true
ClockTime t5 = new ClockTime(12, 53, "PM");   // true
ClockTime t6 = new ClockTime( 3, 15, "PM");   // true
ClockTime t7 = new ClockTime( 4, 59, "PM");   // true
ClockTime t8 = new ClockTime( 5, 00, "PM");   // true
ClockTime t9 = new ClockTime( 5, 01, "PM");   // false
ClockTime ta = new ClockTime( 8, 30, "PM");   // false
ClockTime tb = new ClockTime(11, 59, "PM");   // false
```

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 18: Rectangle union

• Write an instance method `union` that will be placed inside the `Rectangle` class. The method accepts another rectangle r as a parameter and turns the current rectangle into the union of itself and r; that is, modifies the fields so that they represent the smallest rectangular region that completely contains both this rectangle and r.
• For example, the following calls would produce the following rectangles:
```Rectangle rect1 = new Rectangle(5, 12, 4, 6);
Rectangle rect2 = new Rectangle(6,  8, 5, 7);
Rectangle rect3 = new Rectangle(14, 9, 3, 3);
Rectangle rect4 = new Rectangle(10, 3, 5, 8);

rect1.union(rect2);   // {(5, 8), 6x10}
rect4.union(rect3);   // {(10, 3), 7x9}
```

Exercise 19: Rectangle contains

• Write an instance method `contains` that will be placed inside the `Rectangle` class. The method accepts integers for x and y as parameters and turns `true` if that x/y coordinate lies within this rectangle. The edges are included; for example, a rectangle with x=2, y=5, width=8, height=10 will return `true` for any point from (2, 5) through (10, 15) inclusive.