Java Reference
In-Depth Information
int variables, x and y . But actually it indicates that each Point object will contain
two int variables inside it, called x and y . If we create 100 Point objects, we'll have
100 pairs of x and y fields, one in each instance of the class.
The Point class isn't itself an executable Java program; it simply defines a new
class of objects for client programs to use. The client code that uses Point will be a
separate class that we will store in a separate file. Client programs can create Point
objects using the new keyword and empty parentheses:
Point origin = new Point();
When a Point object is constructed, its fields are given default initial values of 0 ,
so a new Point object always begins at the origin of (0, 0) unless you change its x or
y value. This is another example of auto-initialization, similar to the way that array
elements are automatically given default values.
The following lines of code form the first version of a client program that uses our
Point class (the code is saved in a file called PointMain.java , which should be in
the same folder or project as Point.java in order for the program to compile suc-
cessfully):
1 // A program that deals with points.
2 // First version, to accompany Point class with state only.
3
4 public class PointMain {
5 public static void main(String[] args) {
6 // create two Point objects
7 Point p1 = new Point();
8 p1.x = 7;
9 p1.y = 2;
10
11 Point p2 = new Point();
12 p2.x = 4;
13 p2.y = 3;
14
15 // print each point and its distance from the origin
16 System.out.println("p1 is (" + p1.x + ", " + p1.y + ")");
17 double dist1 = Math.sqrt(p1.x * p1.x + p1.y * p1.y);
18 System.out.println("distance from origin = " + dist1);
19
20 System.out.println("p2 is (" + p2.x + ", " + p2.y + ")");
21 double dist2 = Math.sqrt(p2.x * p2.x + p2.y * p2.y);
22 System.out.println("distance from origin = " + dist2);
23 System.out.println();
24
 
Search WWH ::




Custom Search