Question

i have a base class Polygon that implemnts an Interface Shape , and another class Triangle that extends Polygon , now in Triangle copy constructor i need to check if the other triangle given is not null pointer but i can't do it because i have to use super() in order to init my points array.

here's my code : Polygon - the abstract class :

public abstract class Polygon implements Shape {
private Point[] points;

/**
 * Build a Polygon that hold a set of Points.
 * 
 * @param points
 *            (Point[])
 */
public Polygon(Point[] points) {
    this.points = points;
}

Triangle the subClass :

public class Triangle extends Polygon {

/**
 * Constructor.
 * Build a Triangle from 3 Point's.
 * @param p1
 * @param p2
 * @param p3
 */
public Triangle(Point p1, Point p2, Point p3) {
    super(new Point[] { p1, p2, p3 });
}

/**
 * Copy constructor.
 * @param other
 */
public Triangle(Triangle other) {
    /*
     * *********************************************
     * 
     * Here is where i want to make the null check .
     * 
     * *********************************************
     */
    super(other.getPoints().clone());
}

Thanks ahead !

Was it helpful?

Solution

Use a static helper method:

public Triangle(Triangle other) {
    super(clonePoints(other));
}

private static Point[] clonePoints(Triangle other) {
     if (other == null) {
         // ...
     }

     return other.getPoints().clone();
}

Also, what I often do is create a more generic helper method as such:

public Triangle(Triangle other) {
    super(neverNull(other).getPoints().clone());
}

private static <S extends Shape> S neverNull(S notNull) {
     if (notNull == null) {
         // throw a meaningful exception 
         // or return a default value for S if possible / reasonable
     }

     return notNull;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top