user2187875
user2187875

Reputation:

how to return a Point in this example

I am trying to return a Point from a circle.java class that extends a shape class. i keep getting a null pointer exception at the moment. i need to retrun the center point using the inherited getPoints(); method but the inhereted method returns a array and value to be returned from circle is not an array. how would i return the center point without makeing a seperate return method. my Shape class is as follows

import java.awt.Point;

public abstract class Shape {
private String  name;
private Point[] points;
protected Shape(){};
protected Shape(String aName) {
    name = aName;
}

public final String getName() {
    // TODO Implement method
    return name;
}

protected final void setPoints(Point[] thePoints) {
    points = thePoints;
}

public final Point[] getPoints() {
    // TODO Implement method
    return points;
}

public abstract double getPerimeter();

public static double getDistance(Point one, Point two) {
    double x = one.getX();
    double y = one.getY();
    double x2 = two.getX();
    double y2 = two.getY();
    double x3 = x - x2;
    double y3 = y - y2;
    double ypow = Math.pow(y3, 2);
    double xpow = Math.pow(x3, 2);
    double added = xpow + ypow;
    double distance = Math.sqrt(added);
    return distance;
}
}

my circle class is a follows

import java.awt.Point;

public class Circle extends Shape{

private double radius;

public Circle(Point center, int aradius) {
super("Circle");

radius = aradius;
if(radius < 0){
    radius = 0;
}
else{
radius = aradius;
}

}

@Override
public double getPerimeter() {
double perim = 2 * Math.PI * radius;
return perim;
}
  public double getRadius(){
  return radius;
}

}

Upvotes: 0

Views: 1055

Answers (2)

Alowaniak
Alowaniak

Reputation: 600

The reason you're getting a NullPointerException is because you never setPoints of Shape.

I'm not sure what points is supposed to contain but the only thing that would kind of make sense to me is all the points within the shape. Which IMO gets a bit tricky to determine with shapes like circles and determining a center point seems even trickier (although I guess for a circle it would pretty much be the middle point of the array depending on the order?).

(On second thought points could also contain whatever the subclass decides it should, like 1 center point for a circle and 4 points for a rectangle..)

Anyway you will have to fill the points array of Shape (by calling setPoints) with some data before you can use getPoints.

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347284

The simplest solution I can think of is simply to use the setPoints method from the Shape class...

public Circle(Point center, int aradius) {
    super("Circle");
    //...
    setPoints(new Point[]{center});
}

Upvotes: 1

Related Questions