0% found this document useful (0 votes)
16 views4 pages

Java 2D Point Class Implementation

The document describes a Java class called MyPoint that models a 2D point with x and y coordinates, including constructors, methods for setting and getting coordinates, and calculating distances. It also includes a TestMyPoint program that tests the functionality of the MyPoint class by creating instances, modifying coordinates, and calculating distances. The output demonstrates the successful execution of the test cases, showing the coordinates and distances calculated.

Uploaded by

indusindu72
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views4 pages

Java 2D Point Class Implementation

The document describes a Java class called MyPoint that models a 2D point with x and y coordinates, including constructors, methods for setting and getting coordinates, and calculating distances. It also includes a TestMyPoint program that tests the functionality of the MyPoint class by creating instances, modifying coordinates, and calculating distances. The output demonstrates the successful execution of the test cases, showing the coordinates and distances calculated.

Uploaded by

indusindu72
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Program 04 : 2D Point Class

A class called MyPoint, which models a 2D point with x and y coordinates, is designed as follows:

●​ Two instance variables x (int) and y (int).

●​ A default (or “no-arg”) constructor that construct a point at the default location of (0, 0).

●​ A overloaded constructor that constructs a point with the given x and y coordinates.

●​ A method setXY() to set both x and y.

●​ A method getXY() which returns the x and y in a 2-element int array.

●​ A toString() method that returns a string description of the instance in the format “(x, y)”.

●​ A method called distance(int x, int y) that returns the distance from this point to another point
at the given (x, y) coordinates

●​ An overloaded distance(MyPoint another) that returns the distance from this point to the
given MyPoint instance (called another)

●​ Another overloaded distance() method that returns the distance from this point to the origin
(0,0) Develop the code for the class MyPoint. Also develop a JAVA program (called
TestMyPoint) to test all the methods defined in the class.

[Link]

public class MyPoint {

private int x;

private int y;

// Default constructor

public MyPoint() {

this.x = 0;

this.y = 0;

// Overloaded constructor

public MyPoint(int x, int y) {

this.x = x;

this.y = y;
}

// Set both x and y

public void setXY(int x, int y) {

this.x = x;

this.y = y;

// Get x and y in a 2-element int array

public int[] getXY() {

return new int[]{x, y};

// Return a string description of the instance in the format "(x, y)"

public String toString() {

return "(" + x + ", " + y + ")";

// Calculate distance from this point to another point at (x, y) coordinates

public double distance(int x, int y) {

int xDiff = this.x - x;

int yDiff = this.y - y;

return [Link](xDiff * xDiff + yDiff * yDiff);

// Calculate distance from this point to another MyPoint instance (another)

public double distance(MyPoint another) {

return distance(another.x, another.y);

}
// Calculate distance from this point to the origin (0,0)

public double distance() {

return distance(0, 0);

[Link]

public class TestMyPoint {

public static void main(String[] args) {

// Creating MyPoint objects using different constructors

MyPoint point1 = new MyPoint();

MyPoint point2 = new MyPoint(3, 4);

// Testing setXY and getXY methods

[Link](1, 2);

[Link]("Point1 coordinates after setXY: " + [Link]()[0] + ", " + [Link]()[1]);

// Testing toString method

[Link]("Point2 coordinates: " + point2);

// Testing distance methods

[Link]("Distance from Point1 to Point2: " + [Link](point2));

[Link]("Distance from Point2 to Origin: " + [Link]());

This TestMyPoint program creates two MyPoint objects, sets and retrieves coordinates, and tests the
various distance calculation methods. Feel free to modify and expand this code as needed.

Output
$ java TestMyPoint

Point1 coordinates after setXY: 1, 2

Point2 coordinates: (3, 4)

Distance from Point1 to Point2: 2.8284271247461903

Distance from Point2 to Origin: 5.0

Common questions

Powered by AI

The TestMyPoint program verifies the MyPoint class by creating object instances using both constructors, modifying coordinates with setXY(), and retrieving them with getXY(). It also tests the toString() and various distance methods. Additional tests could include boundary tests, such as very large or very small coordinate values, and assertions to automate and verify the correctness of the results against expected outcomes. Integration tests that incorporate MyPoint objects into larger systems could also be added to assess widespread functionality and performance stability under diverse conditions .

Inheritance could be used to extend the functionality of the MyPoint class by creating subclasses that represent more specific types of points or add additional behaviors. For example, a subclass such as ColoredPoint could include a color property, adding visual attributes to the basic x and y coordinates. Another possibility is a subclass like LabeledPoint that includes a descriptive label for the point. In both cases, the subclasses would extend the MyPoint class and possibly override or add new methods to handle these additional properties, while retaining the core functionality of point coordinates and distance calculations .

The MyPoint class uses two types of constructors for initialization: a default constructor and an overloaded constructor. The default constructor initializes a point at (0, 0), which is useful when no specific coordinates are provided. This can be particularly beneficial if you want a base object without conditions. The overloaded constructor requires specific x and y coordinates, allowing for more precise initialization when specific values are known and needed immediately. Using a default constructor can simplify creation when defaults are acceptable, while the overloaded constructor ensures specific data encapsulation from the start .

Immutability could be integrated into the MyPoint class by preventing modification of the x and y fields after object creation, possibly by omitting methods like setXY() or providing x and y through final fields. This design ensures that once a MyPoint object is created, it remains unchanged, reducing the risk of inadvertent side effects and improving thread safety in concurrent applications. With immutable objects, predictability and maintainability of code enhance, while often simplifying debugging due to a consistent state .

The MyPoint class uses double for its distance calculations, providing sufficient precision for most applications. However, in scenarios requiring ultra-high precision, such as scientific simulations or financial computations, even doubles can fall short. Potential improvements include using BigDecimal, which supports arbitrary-precision arithmetic, although at the cost of performance. Another option is to implement mechanisms that dynamically adjust precision based on application needs, ensuring both accuracy and efficiency .

In the MyPoint class, method overloading is used to define multiple distance methods that can calculate distances under different circumstances. The method distance(int x, int y) calculates the distance to a point given specific coordinates, while distance(MyPoint another) uses another MyPoint object as a reference. Additionally, the overloaded distance() method computes the distance to the origin (0,0). This use of method overloading enhances flexibility and simplicity, allowing users to choose the most suitable method according to their specific needs, without altering the class structure or duplicating code unnecessarily .

The toString() method in the MyPoint class provides a straightforward way to convert the object into a human-readable string format, "(x, y)". This is significant for debugging and logging, as it allows developers to easily interpret the current state of an object in a format that is clear and concise. It enhances code readability and assists in identifying the object's data at any point during execution without manually extracting the properties .

The getXY() and setXY() methods in the MyPoint class encapsulate data by controlling access to the instance variables x and y. setXY() allows controlled modification of these variables outside the class, ensuring that any logic required for setting new values can be centralized in one place. Meanwhile, getXY() provides a safe way to retrieve these values by returning them in a protected manner, without exposing the internal structure directly. This encapsulation maintains internal data integrity while providing necessary functionality .

The MyPoint class could be used in GPS-based applications such as mapping software and navigational systems, where points on a 2D plane often represent waypoints or destinations. By leveraging the distance methods, these applications can calculate distances between various points, helping to determine shortest paths or proximity-based searches. The ability to easily instantiate points, set new coordinates, and retrieve them makes MyPoint adaptable for real-time location updates and geographic visualizations in dynamic map systems .

The distance methods in the MyPoint class compute Euclidean distances, which involve squaring two differences and taking a square root. While this calculation is robust, it might not be the most efficient for applications needing quick and frequent distance checks, such as in simulations or real-time calculations. One improvement could involve using squared distances only, which avoids the computationally intensive square root function, and can be sufficient when relative distances or comparisons are needed. However, for exact distance measures, these methods are efficient and straightforward .

You might also like