Sco*_*ott 5 java nullpointerexception abstract
我试图简单地在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();
}
Run Code Online (Sandbox Code Playgroud)
和孩子班:
public class Ellipse extends Shape {
public Ellipse() {
}
public double calcArea() {
return 0.0;
}
public boolean draw() {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
你可能想看点:
public class Point {
public double locationX;
public double locationY;
public Point() {
locationX = 0.0;
locationY = 0.0;
}
}
Run Code Online (Sandbox Code Playgroud)
最后主要功能:
public class MakeShapes {
public static void main(String []args) {
Ellipse myShapes = new Ellipse();
myShapes.setLocation( 100.0, 100.0 );
}
}
Run Code Online (Sandbox Code Playgroud)
一旦我使用setLocation(),我就会获得NPE.有什么想法吗?试图解决这个问题,我的大脑很痛.谢谢!!!
这里的问题是你的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();
}
Run Code Online (Sandbox Code Playgroud)
这是一个微妙的错误。您正在创建一个局部center变量,但没有将其分配给this.center
public Shape() {
Color color = Color.BLACK;
Point center = new Point();
rotation = 0.0;
System.out.println("shape created");
}
Run Code Online (Sandbox Code Playgroud)
color将和声明更改center为this.
this.center = new Point()
最终this.center从未真正定义过,因此是 NPE。