0

有一个接口

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();
    }
}

我不明白构造函数有什么问题。我将不胜感激任何建议。

4

3 回答 3

8

看这部分:

private Point a;
...

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

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

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 个参数,而您的原始代码使用x1and y1

我还鼓励您更多地考虑点 - 我将重写接口和构造函数以使用Point值而不是个体xy值。

于 2013-07-23T21:00:03.627 回答
0

你永远不会实例化Points 中使用的 s RightTriangle

您既没有提供 aPoint实际上是什么,但您肯定需要RightTriangle在一开始就使用 in s 构造函数:

this.a = new Point();
this.b = new Point();
this.c = new Point();
于 2013-07-23T21:00:45.803 回答
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
于 2013-07-23T21:00:46.803 回答