无法使用构造函数创建对象

时间:2013-07-23 20:58:07

标签: java constructor nullpointerexception

有一个界面

public interface Rtriangle {
    int getApexX1();
    int getApexY1();
    int getApexX2();
    int getApexY2();
    int getApexX3();
    int getApexY3();
}

实现此接口的类

public class RightTriangle implements Rtriangle{
    private Point a;
    private Point b; 
    private Point c;

    public RightTriangle (int x1, int y1, int x2, int y2, int x3, int y3){
        this.a.x=x1;
        this.a.y=y1;
        this.b.x=x1;
        this.b.y=y1;
        this.c.x=x1;
        this.c.y=y1;
} 

    public int getApexX1(){
        return a.x;
        }
    public int getApexY1(){
        return a.y;
    }
    public int getApexX2() {
        return b.x;
    }
    public int getApexY2(){
        return b.y;
    }
    public int getApexX3(){
        return c.x;
    }
    public int getApexY3(){
        return c.y;
    }
}

还有一个类使用这个类:

public class RtriangleProvider {
    public static Rtriangle getRtriangle(){
        try{
            Rtriangle tr = new RightTriangle(0, 0, 0, 2, 2, 0);
            return tr;
        }
        catch(Exception e){
            System.out.print(e.toString());
            return null;
        }
    }
}

当我尝试使用getRtriangle()方法时,我在此行上收到NullPointerException异常:

 Rtriangle tr = new RightTriangle(0, 0, 0, 2, 2, 0);

关于RightTriangle的创作。

public class TestTriangle {
    @Test
    public void testRight(){
        Rtriangle tr =RtriangleProvider.getRtriangle();
    }
}

我无法理解构造函数有什么问题。我会很感激任何建议。

3 个答案:

答案 0 :(得分:8)

看看这部分:

private Point a;
...

public RightTriangle (int x1, int y1, int x2, int y2, int x3, int y3){
    this.a.x=x1; 
    ...
}

您期望a的价值在这里?它没有被其他任何东西设置,所以它将为null。取消引用它然后导致异常。我怀疑你想要:

public RightTriangle (int x1, int y1, int x2, int y2, int x3, int y3){
    a = new Point(x1, y1);
    b = new Point(x2, y2);
    c = new Point(x3, y3);
}

另请注意,此代码使用所有6个参数,而原始代码使用x1y1

我还鼓励你从点数来考虑更多 - 我会重写接口和构造函数以使用Point值,而不是单独的xy值。

答案 1 :(得分:0)

您永远不会实例化Point中使用的RightTriangle

你既没有提供Point实际上是什么,但你肯定需要在RightTriangle的构造函数中使用:

this.a = new Point();
this.b = new Point();
this.c = new Point();

答案 2 :(得分:0)

this.a.x=x1;构造函数的行RightTriangle等中,您正在访问Point实例字段'公共字段,而不首先初始化Point字段。

因此NPE。

尝试以下方面的内容:

this.a = new Point(); // or whatever is the signature of the Point constructor
this.a.x=x1;
// and so forth