l 0.4 (The Point class) Design a class named MyPoint to represent a point with x
ID: 3778794 • Letter: L
Question
l 0.4 (The Point class) Design a class named MyPoint to represent a point with x- and y-coordinates. The class contains: The data fields x and y that represent the coordinates with getter methods. A no-arg constructor that creates a point (0,0). A constructor that constnicts a noint with specified coordinates. A method name Textbook exercise 10.4 turns the distance from this point to a specified point of the MyPoint type. A method named distance that returns the distance from this point to another point with specified x and y-coordinates. Draw the UML diagram for the class and then implement the class. Write a test program that creates the two points (0, 0) and (10, 30.5) and displays the distance between them.Explanation / Answer
TestMyPoint.java
public class TestMyPoint {
public static void main(String[] args) {
MyPoint p1 = new MyPoint(0,0);
MyPoint p2 = new MyPoint(10, 30.5);
double distance = p1.distance(p2);
System.out.println("Distance is "+distance);
}
}
MyPoint.java
public class MyPoint {
private double x,y;
public MyPoint(){
x =0;
y=0;
}
public MyPoint(double x, double y){
this.x = x;
this.y = y;
}
public double distance(MyPoint p){
return Math.sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y));
}
public double distance(double x, double y){
return Math.sqrt((this.x - x) * (this.x - x) + (this.y - y) * (this.y - y));
}
}
Output:
Distance is 32.09750769140807
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.