Java NullPointerException when called from an abstract class

I am trying to simply extend an abstract class in Java and call several methods stored in it. When I do this, I get a NullPointerException. Am I missing something about abstraction here?

This is the parent class:

public abstract class Shape {
    public Color color;
    public Point center;
    public double rotation;

    public Shape() {
        Color color = new Color();
        Point center = new Point();
        rotation = 0.0;
        System.out.println("shape created");
    }

    public void setLocation( Point p ) { center.locationX = p.locationX; center.locationY = p.locationY; }
    public void setLocation( double x, double y ) { center.locationX = x; center.locationY = y; }

    public abstract double calcArea();
    public abstract boolean draw();
}

And the child class:

public class Ellipse extends Shape {        
    public Ellipse() {
    }

    public double calcArea() {
        return 0.0;
    }

    public boolean draw() {
        return true;
    }
}

You might want to see the item:

public class Point {
    public double locationX;
    public double locationY;

    public Point() {
        locationX = 0.0;
        locationY = 0.0;
    }
}

And finally, the main function:

public class MakeShapes {
    public static void main(String []args) {
        Ellipse myShapes = new Ellipse();
        myShapes.setLocation( 100.0, 100.0 );
    }
}

As soon as I use setLocation (), I get NPE. Any suggestions? My brain hurts trying to figure it out. Thanks!!!

+4
source share
3 answers

, Shape Point, center, ( color). :

public abstract class Shape {
    public Color color;
    public Point center;
    public double rotation;

    public Shape() {
        color = new Color(); //changed to intialize the field
        center = new Point(); //changed to intialize the field
        rotation = 0.0;
        System.out.println("shape created");
    }

    public void setLocation( Point p ) { center.locationX = p.locationX; center.locationY = p.locationY; }
    public void setLocation( double x, double y ) { center.locationX = x; center.locationY = y; }

    public abstract double calcArea();
    public abstract boolean draw();
}
+8

. center this.center

    public Shape() {
        Color color = Color.BLACK;
        Point center = new Point();
        rotation = 0.0;
        System.out.println("shape created");
    }

color center this.

this.center = new Point()

this.center , , NPE.

+4

I agree with the foregoing.

You create an instance of another object inside the constructor, which is removed once from the scope. This way you did not actually set the elements of the object.

0
source

Source: https://habr.com/ru/post/1608375/


All Articles