Building Java Programs

Lab: Classes and Objects

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

Modified by T. W. Bennet

Lab goals

Goals for this problem set:

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 : PointClient

Point and PointMain

Exercise : Make Point Comparable.

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 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).

Note carefully: the method both exchanges the x and y values, and changes the sign of each one.

Test your code by uncommenting the code in PointMain for testing flip, and running the program again.

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 Class

Exercise : Rectangle corners

Exercise : Rectangle contains

Exercise : Rectangle overlap