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か? 他に設定されていないため、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

于 2013-07-23T21:00:03.627 に答える