Title: Classes Part 3: Summary, Constructors
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Classes Part 3

This image provides a review of many of the class concepts covered so far.

Additional Points to make

1. Methods can return any primitive or any class. Consequently, you can use a method anyplace place that the returned item could be used. For example:

System.out.println("area = " + r1.getArea( ) );
2. Note that with a class, you can call the method without any "object." in front of the method. Notice the calls to inside in the overlaps routines. However, in main the same call would be made like:
r1.inside(.....);
Just like the case with instance variables, you could imagine inside the class something like:
this.inside(.....)
3. Local Variables - Our rectangle class has no local variables, so look at the readInput routine in DateSixthTry. Note the 2 local variables there. These variables go away when we exit readInput. Furthermore these variables are only seen in readInput. Also if the same names showed up in another routine, there would be no conflict.
4. Local Variables within "curly braces" or blocks of code as are temporary to the block where they are defined.
5. An example of a Local variable is counter defined within a for loop.

Constructors:

Points-

1. A class always has at least one constructor. If you don't create one, a default constructor is provided by the compiler. This is what we have been using in our classes so far.
2. Demo what the compiler provided.
3. In general, the job of a constructor is to do any initialization required for your class. It is always preferrable to make sure everything is initialized before you class is used. Some of the initialization can come as part of the instance variable declaration.
4. Put a print statement into a constructor and show that it gets called as part of the "new" statement. Note that a constructor only gets called once and it is the first thing to execute in your class and it always exectutes as a result of the "new" operation which also allocates memory.
5. Create a constructor that matches the setRectangle methods and demo their usage.
6. Note that providing any constructor results in the compiler not providing a default constructor.
7. A constructor always has the name of the associated class. A constructor looks like a method except that it has no return. In fact if you add any return (even void), the constructor seizes to be a constructor and becomes a regular method.
8. Suppose that you have multiple constructors and you have some code that you don't want to replicate for every constructor. For example, have the Rectangle constructor check for height and width being > 0.
9. Demo having the Rectangle constructor that uses Point to call(using "this") the constructor that gets passed all ints.
10. Note that if you use "this" to call a constructor, it must be the very first executable statement within the constructor.
11. Go to chapter 4 textbook examples and look at the constructors in the author's final Date class for the chapter.
12. Note that the following are equivalent:
Rectangle r1 = new Rectangle();
and
Rectangle r1; // defaults to null at this point. It may be necessary to set it to null
r1 = new Rectangle();
13. I mentioned that a Rectangle is only constructed once. However, it is possible for a variable to receive a constructed object multiple times. For example:
Rectangle r1 = new Rectangle();
r1 = new Rectangle(1,2,3,4);
14. Constructed classes are allocated in a memory space called the "heap". When the address of a constructed object is no longer saved by any reference, it becomes "orphaned" and it is available for garbage collection whenever the system is low on memory and needs to find any unused "orphaned" memory.

In the Video, the previous Rectangle is updated. The following highlights the final version created from the video


class Point
{
    int x, y;
    Point (int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}


public class Rectangle {
    private int x=0, y=0, width=1, height=1;

    //default constructor
    public Rectangle()
    {
    }

    // This constructor initializes similar to the following setRectangle method.
    public Rectangle(int x, int y, int width, int height)
    {
        // Note this constructor calls the constructor: Rectangle (Point p1, Point p2)
        this( new Point(x,y),    new Point(x+width, y+height));
    }
    public void setRectangle(int x, int y, int width, int height)
    {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

 // This constructor initializes similar to the following setRectangle method.
    public Rectangle (Point p1, Point p2){
        setRectangle(p1,p2);
    }
    public void setRectangle(Point p1, Point p2)
    {
        x = min(p1.x, p2.x);
        y = min(p1.y, p2.y);
        width = abs(p1.x - p2.x);
        height = abs(p1.y - p2.y);
    }
    private int min(int v1, int v2)
    {
        if (v1 < v2)
            return v1;
        else
            return v2;
    }
    private int abs(int v1)
    {
        if (v1 >= 0)
            return v1;
        else
            return -v1;
    }


    public String toString()
    {
        return x + ":" + y + ":" + width + ":" + height;
    }

    public int getArea()
    {
        return width * height;
    }
    public int getPerimeter()
    {
        return 2* (width + height);
    }
    boolean equals(Rectangle otherRect)
    {
        if (x == otherRect.x && this.y == otherRect.y &&
                width == otherRect.width && height == otherRect.height)
            return true;
        else
            return false;
    }

    boolean inside (int xp, int yp)
    {
        if (xp >= x && xp <= (x+width) &&
                yp >= y && yp <= y+height)
            return true;
        else
            return false;
    }

    boolean overlaps( Rectangle r)
    {
        if (inside(r.x, r.y)  || inside( (r.x+r.width), r.y) ||
                inside (r.x, r.y + r.height) || inside (r.x+r.width, r.y+r.height))
                return true;
        else
            return false;
    }

    public static void main(String[] args) {
        Rectangle r1 = new Rectangle();

        //this.someVar = 8;

        byte b1=0, b2=0, b3=5;
        long l4 = 3;

        r1.setRectangle(b1, b2, b3, (int)l4);
        System.out.println( r1.toString());

        System.out.println("area =" + r1.getArea());
        System.out.println("perimeter =" + r1.getPerimeter());

        Rectangle r2 = new Rectangle();
        r2.setRectangle(3, 2, 5, 3);

        if (r1.equals(r2))
            System.out.println("Rectangles are EQUAL");
        else
            System.out.println("Rectangles are NOT EQUAL");

        if (r1.overlaps(r2))
            System.out.println("r1 and r2 overlap");


    }

}




Java Practice(JPHM):

Add the Rectangle class shown above to your package. Follow the specifications below to create 3 rectangles using the added Rectangle class.

- (1 point) Rectangle r1 will be created with the default constructor and initialized by calling setRectangle with values: 1, 2, 3, 4
- (1 point) Rectangle r2 will be created with the constructor that takes 2 Point class objects. Pick values such that r1 and r2 are essentially the same Rectangle. HINT: consider Points with coordinates (1,2) and (4,6)
- (1 point) Rectangle r3 will be created with the constructor that takes 4 integers. Choose the values 10, 20, 30, 40.

Now demonstrate the following using the methods in the Rectangle class:

1. (1 point) Compute the area of r1.
2. (1 point) Compute the perimeter of r3.
3. (2 points) Find out if r1 overlaps r2.
4. (1 point) Find out if r1 overlaps r3
5. (1 point) Find out if r2 equals r3.
6. (1 point) Find out if r1 equals r2.

Last Modified: December 22, 2014 10:56 PM