02. In this question we will step you through implementing classes and methods i
ID: 3742104 • Letter: 0
Question
02. In this question we will step you through implementing classes and methods in Java for a new ride-sharing app called Rebu. Rebu connects passengers looking for a ride with drivers in their area. You can assume that the classes or methods in earlier questions "exist" in later questions, even if you haven't answered the question. You must follow proper Object Oriented Design principles, and Java programming conventions. Write all class declarations. Do not write method signatures that are given to you. [30 MARKS (a) Implement an immutable Position class. A Position is defined by its x and y coordinate. Your class should include a constructor, and appropriate getters and settersExplanation / Answer
public final class Position {
final private double x;
final private double y;
/** instantiate a point
* "this.x" refers to the instance variable of the object
* x refers to the parameter
* same for this.y and y
*/
public Position(double x, double y){
this.x = x;
this.y = y;
}
/**
* Position() creates the origin by appropriately calling
* the general Position constructor
*/
public Position(){
this.x = 0;
this.y = 0;
}
/**
* @return x
*/
public double getX(){
return x;
}
/**
* @return y
*/
public double getY(){
return y;
}
/**
* convert to String
*/
public String toString(){
return "("+x+","+y+")";
}
/**
*
* @param p other point
* @return test for equality using epsilon, because we
* are dealing with doubles,so roundoff can occur
*/
public boolean equals (Position p){
if (this.x==p.x && this.y==p.y)
return true;
return false;
}
/**
* We need this equals method for ArrayList<Position>, because
* the generic ArrayList is really an ArrayList of Object.
* In the case of equals, the signature is
* public boolean equals(Object o)
* and the method below overrides the Object equals method
* and the calls the class's equals(Position) method
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj){
if (obj instanceof Position){
Position p = (Position)obj;
return equals(p);
}
return false;
}
/**
*
* @param p
* @return Euclidean distance of this point to Position p
*/
public double euclidDist(Position p){
return Math.sqrt((this.x - p.x) *(this.x - p.x) + (this.y - p.y) *(this.y - p.y) );
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.