Key Points from WEEK 14 11/29/2023 Lecture We have seen how to declare a variable of a specified data type, as in: int a; or int x1; int y1; int x2; int y2; or double x1; double y1; double x2; double y2; Sometimes we would like to be able to declare a variable to refer to a more complex type. For example, if we are developing a graphics application such as a game, or a physical simulation, we might want to keep track of objects that are constructed from points. In such cases, we might want to be able to declare a single variable to represent a point as in: Point p1; In order to be able to declare a Point variable in this way, there needs to be a class called Point. The following would suffice: public class Point { public double x; public double y; // Point class' constructor public Point(double x, double y) { this.x = x; this.y = y; } public String toString() { return "(" + x + "," + y + ")"; } } The above code defines a *class* called Point, which describes what a Point *object* is. Whereas an int variable holds a single integer value, a Point object holds two values, one for the x coordinate and one for the y coordinate. With this class definition we can now instantiate a point object: p1 = new Point(1,2); This causes a Point object (an instance of the Point class) to be created and a reference to this new object to be stored in the variable p1. The code in the Point class' *constructor* initializes the double x and double y fields of the new Point object with the argument values 1 and 2, respectively. Given p1, we can refer to the x coordinate of p1 as p1.x and the y coordinate of p1 as p1.y: System.out.println("p1.x = " + p1.x); // This will print 1 to the console System.out.println("p1.y = " + p1.y); // This will print 2 to the console It is possible to create multiple instances of the Point class: Point p2 = new Point(4,2); Point p3 = new Point(4,6); Each of p1, p2, and p3 will have its own x,y coordinates. There is another major component of the Point class besides the declaration of the x and y variables. There is a definition of a method called toString(). In addition to specifying what variables a Point object has (what variables hold a Point object's *state*), the class also defines the *behavior* of a Point object. If we wanted to, we could define operations that a Point can perform, such as operations that will change the x,y coordinates, like translate() or rotate(). This would be part of the behavior of the Point. In the next lab we will see the example of a Polygon class that is composed of an array of Points and has various methods such as translate(), rotate(), scale(), perimeter(), and area(), some of which can change a Polygon's state, and some of which just report its state or the results of calculations based on its state.