Java lets us program with objects. We use classes, one per file, to describe how these objects work -- a blueprint, if you will. Here is the code for a simple class that represents a 2-dimensional point:
public class Point2d { // Some private data members private int xCoordinate; private int yCoordinate; // Regular constructor: takes two arguments. public Point2d(int x, int y) { this.xCoordinate = x; this.yCoordinate = y; } // No-argument constructor: defaults to a point at the origin. public Point2d() { this.xCoordinate = 0; this.yCoordinate = 0; } // "Accessor" methods public int getX() { return xCoordinate; } public int getY() { return yCoordinate; } // "Mutator" methods public void setX(int value) { this.xCoordinate = x; } public void setY(int value) { this.yCoordinate = y; } }
This code must be saved in a file called Point2d.java, which is provided for your consumption. You might save a copy of it to your working directory and build off of it for this lab.
Recall that we can instantiate our class anywhere else in our code by calling any of the constructors we've defined, like so:
Point2d myPoint = new Point(); // creates a point at (0,0) Point2d myOtherPoint = new Point(5,3); // creates a point at (5,3) Point2d aThirdPoint = new Point();
Be careful: myPoint != aThirdPoint! This is because the comparison operator (and its opposite) compare the two object references. Each of myPoint and aThirdPoint refers to a different instance of the Point2d class. It is true in this case that the private data members are the same, and as humans we would probably agree that these two Point2d's are "equal."
To test for object equality and not reference equality, define a method of the Point2d class called equals which takes another Point2d as an argument and explicitly compares the internal data members:
public boolean equals(Point2d other) { if (this.xCoordinate != other.getX()) return false; if (this.yCoordinate != other.getY()) return false; // okay, these are "equal" return true; }
It should not be possible to:
> javac Point3d.java Lab2.javaand then run your Lab2 program, testing it with several sample triangles.
~/cs11/java/lab2on the CS cluster and make sure it is world-readable. (If you don't know, it is.)