0

I have one class called Square that exetnds a class called Shape. In my main, I instantiating it like this:

Point p1 = new Point(3,3); 

Shape s1 = new Square(p1,3); 

I am getting the following error when I compile it:

Exception in thread "main" java.lang.NullPointerException
at Shape.<init>(Shape.java:19)
at Square.<init>(Square.java:18)
at mine.main(mine.java:16)

I have one superclass called Shape implemented like this:

  abstract class Shape implements Comparable<Shape> {
  public Point position;

  public Shape(Point p){
    position.x  = p.x;      //Line 19
    position.y  = p.y;
  }
}

Point is the following class:

public final class Point {
  public double x;
  public double y;

  // constructor that sets the values of x and y
  public Point(double num1, double num2)
  {  
    this.x = num1;
    this.y = num2;
  }
}

Square is the following class:

class Square extends Shape {
  private double side; // side is the side length

  public Square(Point p0, double side)
  {  
    super(p0);               // Line 18
    this.side = side;
  }
Pape Sow Traore
  • 179
  • 1
  • 3
  • 14

2 Answers2

4

You never initialized position in class Shape.

What you probably wanted to do

public Shape(Point p){
   position = p;
}

Or, at the very least (if you wanted to "clone" the Point)

public Shape(Point p){
   position = new Point(p.x, p.y);
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
2
position.x  = p.x;      //Line 19

position is not initialized when this line is executed. You'd better do something like this:

  public Shape(Point p){
    position = p;
  }
Andres
  • 10,561
  • 4
  • 45
  • 63