Reputation: 63
I have run into a problem on a piece of homework I have. I've had to make my own Shape
, Circle
and Rectangle
classes. The problem is when a Point
object is inputted into a circle and rectangle, the Shape class won't accept it in the constructor for a new shape object.
So when I run the main program, the coordinates of the centre of the circle and top corner of the rectangle are null instead of the inputted coordinates.
How can I get Shape
to accept the point coordinates?
(Sorry if the codes/terminology's wrong, I'm still new to Java)
My shape class:
public class Shape {
private int sides;
private Color colour;
private Point coordinates;
public Shape (int sides, Point coordinates, Color colour) {
this.sides = sides;
this.colour = colour;
this.coordinates = coordinates;
}
My Circle class:
public class Circle extends Shape {
private Point center;
private int radius;
//constructor for circle class
public Circle(Point center, int radius, Color c) {
super(0, center, c);
this.radius = radius;
My rectangle class:
public class Rectangle extends Shape {
private int sides = 4;
private Point topCorner;
private int width, length;
//Constructor for rectangle
public Rectangle(Point topCorner, int width, int length, Color c) {
super(4, topCorner, c);
this.width = width;
this.length = length;
}
My main class:
public static void main(String[] args) {
Point p1 = new Point(0,20);
Point p2 = new Point(20,0);
Point p3 = new Point(30,30);
Shape r = new Rectangle(p1, 10, 15, Color.BLUE);
Shape c = new Circle (p3, 25, Color.YELLOW);
Upvotes: 0
Views: 58
Reputation: 11947
It's because you never initialise topCorner
or center
.
In your Circle
constructor, add
this.center = center;
In your Rectangle
constructor, add
this.topCorner = topCorner;
But, to be honest, what is the purpose of center
and topCorner
? Shape#coordinates
will be the coordinates you are looking for. No need to create another Point
object in your subclasses when it can be accessible from your super class.
Upvotes: 1