Consider a Coordinate base class or interface and Coordinate1D, Coordinate2D, an
ID: 3673823 • Letter: C
Question
Consider a Coordinate base class or interface and Coordinate1D, Coordinate2D, and Coordinate3D classes, each of which can be initialized with a specific value or, alternately, will initialize itself with a random value. Each should implement:
-- toString(), but the details of formatting are up to you.
-- distance(), which returns the linear distance between two coordinates of the same type, e.g. 1D, 2D, or 3D. It takes another coordinate as an argument and should throw an exception if it is the wrong type of coordinate
-- label(), which labels the provided point with the provided string
-- getLabel(), which returns the label associated with the point.
Please design and implement the four classes described above, and a CoordinateFactory to create them. Prove that your solution works by writing a brief example program that shows the factory creating more than one type of coordinate.
Explanation / Answer
The desired solution is as below, there is one interface and 3 classes implementing the same interface.
There is one factory to initialise the required coordinate class based on the input parameters.
//The coordinate interface
public interface ICoordinate {
String toString();
double distance(int[] points);
void label();
String getLabel();
}
//Class for coordinate1D
public class Coordinate1D implements ICoordinate{
private int x;
public Coordinate1D(int x){
this.x = x;
}
public String toString(){
}
public double distance(int[] points){
if(points.length > 1){
throw new Exception("Invalid coordinate type");
}
}
public void label(){
}
public String getLabel(){
}
}
//Class for coordinate2D
public class Coordinate2D implements ICoordinate{
private int x, y;
public Coordinate2D(int x, int y){
this.x = x;
this.y = y;
}
public String toString(){
}
public double distance(int[] points){
if(points.length !=2){
throw new Exception("Invalid coordinate type");
}
}
public void label(){
}
public String getLabel(){
}
}
//Class for coordinate3D
public class Coordinate3D implements ICoordinate{
private int x, y, z;
public Coordinate3D(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
public String toString(){
}
public double distance(int[] points){
if(points.length !=3){
throw new Exception("Invalid coordinate type");
}
}
public void label(){
}
public String getLabel(){
}
}
///Factor to initialise different types of coordinate based on coordinates
public class CoordinateFactory{
public ICoordinate CreateCoordinate(int[] points){
int length = points.length;
switch(length){
case 1:
return new Coordinate1D(points[0]);
case 2:
return new Coordinate2D(points[0], points[1]);
case 3:
return new Coordinate3D(points[0], points[1],points[2]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.