2015-09-21 33 views
4

我想簡單地在Java中擴展一個抽象類並調用存儲在其中的幾個方法。當我這樣做時,我一直在收到NullPointerException。我在這裏錯過了關於抽象的東西嗎?從抽象類調用時發生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。有什麼想法嗎?我的腦子因試圖弄清楚而感到痛苦。謝謝!!!

+1

請提供異常的堆棧跟蹤,並在代碼中指明它出現的位置。 –

回答

4

這是一個微妙的錯誤。您正在創建一個本地center變量,而不是在分配給this.center

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

變化colorcenter聲明是this.

this.center = new Point()

到底this.center不會真正定義,因此NPE。

+0

嘉清!!!是的,這將做到這一點。我一直在看這個這麼久......並且一如既往,這是一個簡單的錯誤......謝謝! –

8

這裏的問題是,你的Shape構造函數創建一個本地Point參考稱爲center和initilizes的那一個,而不是intializing場(和你有同樣的問題與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(); 
} 
0

我同意以上所述。

您正在構造函數內創建另一個對象的實例,該實例在超出範圍時被刪除一次。 所以,你實際上並沒有設置對象的成員。

相關問題