我试图简单地扩展 Java 中的抽象类并调用存储在其中的一些方法。当我这样做时,我不断收到 NullPointerException。我在这里是否遗漏了一些关于抽象的东西?
这是父类:
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();
}
还有子类:
public class Ellipse extends Shape {
public Ellipse() {
}
public double calcArea() {
return 0.0;
}
public boolean draw() {
return true;
}
}
你可能想看点:
public class Point {
public double locationX;
public double locationY;
public Point() {
locationX = 0.0;
locationY = 0.0;
}
}
最后是主要功能:
public class MakeShapes {
public static void main(String []args) {
Ellipse myShapes = new Ellipse();
myShapes.setLocation( 100.0, 100.0 );
}
}
只要我使用 setLocation(),我就会得到 NPE。有什么想法吗?我的大脑因试图弄清楚这一点而受伤。谢谢!!!
最佳答案
这里的问题是您的 Shape
构造函数创建了一个名为 center
的本地 Point
引用并初始化了该引用而不是初始化字段(并且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();
}
关于从抽象类调用时出现 Java NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32704421/