Example constructor in java point class with x and y coordinate system and program to find distance between two points


java-point-class-example

In java point class of object oriented programming, it usually has two
instance variables which are x and y, standing for java cooidinate class.  We
use private to declare instance variables to make those variables hide from other classes.
           
            In this tutorial, constructor in java point class usually is Point(int x, int y). X and Y are two integer values being passed into the point constructor.  In the constructor,we simply set x and y values of the point object equal to their new values.

            We could create getter methods, they will help us to get x and y values, and setter methods, it will set x and y values equal to their new values. The toString() will display x and y values by a string which we want to define.

            Move by method and move to method are two basic method in java point class. MoveBy() method will move x and y values of the object point by plus them with another x and y values of another point which is passed into the method.MoveTo() method will move x and y of the object point to the new x and new y of the passing point by set x and y of object point equal x and y of passing point.


java-point-class-example-1
Divide() method will divide x and y by an integer number. The asNegative() method simply makes x and y values of passing point become negative in order to use it to make minus() method.

java-point-class-example-2

The distance between two points in java program is usually calculated with a simple formula: in this method, we use Math.round to round our result and cast the result to integer type by (int).


java-point-class-example-3
We create a main entry in Point class to test our methods.

java-point-class-example-4

The final result.

Read more about learn java point tutorial:

Comments

Post a Comment