Search code examples
javaarraysinterfaceabstract-classsuper

Exception when trying to make a super call to abstract class


I am quite new to Java. This is a project I am working on for class, in which I have to implement abstract classes and interfaces in order to build a polygon hierarchy. However, I can tell there's something wrong in the code somewhere. I have an interface Polygon() that defines 3 functions and an abstract class SimplePolygon() that implements said interface. I think I may be doing my for loop wrong here but I'm not sure. The array has to be different sizes depending on if it's a triangle or other shape so I can't just hard code a size of 3.

public abstract class Simple_Polygon implements Polygon
{
    protected Point vertices[];
    
    public Simple_Polygon(int vertAmount)
    {
        if (vertAmount < 3)
        {
            throw new IllegalArgumentException("A polygon has 3 vertices or more!");
        }

        for (int i = 0; i < vertAmount; i++)
        {
            vertices[i] = new Point(0, 0);
        }
        
    }
}

Then I have class Triangle() that extends Polygon().

public class Triangle extends Simple_Polygon
{
    public Triangle(Point p1, Point p2, Point p3)
    {
        super(3);
        
        vertices[0] = p1;
        vertices[1] = p2;
        vertices[2] = p3;
        
    }
}

And finally I have a tester class which was written by the teacher that creates the Triangle object. However, every time I run it I get

Exception in thread "main" java.lang.NullPointerException: Cannot store to object array because "this.vertices" is null
    at polygons.Simple_Polygon.<init>(Simple_Polygon.java:23)
    at polygons.Triangle.<init>(Triangle.java:14)

Which are the for loop in the abstract constructor and the super call, respectively. I have tried looking at different questions for abstract vs interface classes, but I can't seem to find anything. I'm thinking it has to do with how I assign values in my array. Anyone have any ideas?


Solution

  • NullPointerException is thrown when you are trying to refer to an object that is declared but not defined.

    In the above example, you are referring to vertices but have never initialized the variable.

    Use the following statement to define the value for vertices

    this.vertices = new Point[vertAmount];

    Full Example in your context.

    public abstract class Simple_Polygon implements Polygon
    {
        protected Point vertices[];
        
        public Simple_Polygon(int vertAmount)
        {
            if (vertAmount < 3)
            {
                throw new IllegalArgumentException("A polygon has 3 vertices or more!");
            }
    
            this.vertices = new Point[vertAmount];
            for (int i = 0; i < vertAmount; i++)
            {
                vertices[i] = new Point(0, 0);
            }
            
        }
    }