0 java constructor nullpointerexception
有一个界面
public interface Rtriangle {
int getApexX1();
int getApexY1();
int getApexX2();
int getApexY2();
int getApexX3();
int getApexY3();
}
Run Code Online (Sandbox Code Playgroud)
以及实现此接口的类
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;
}
}
Run Code Online (Sandbox Code Playgroud)
还有一个类使用这个类:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用getRtriangle()方法时,我在此行上收到NullPointerException异常:
Rtriangle tr = new RightTriangle(0, 0, 0, 2, 2, 0);
Run Code Online (Sandbox Code Playgroud)
在RightTriangle创作.
public class TestTriangle {
@Test
public void testRight(){
Rtriangle tr =RtriangleProvider.getRtriangle();
}
}
Run Code Online (Sandbox Code Playgroud)
我无法理解构造函数的问题.我将不胜感激任何建议.
看看这部分:
private Point a;
...
public RightTriangle (int x1, int y1, int x2, int y2, int x3, int y3){
this.a.x=x1;
...
}
Run Code Online (Sandbox Code Playgroud)
你期望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);
}
Run Code Online (Sandbox Code Playgroud)
另请注意,此代码使用所有6个参数,而您的原始代码仅使用x1和y1.
我还鼓励你从点数来考虑更多 - 我会重写接口和构造函数来使用Point值而不是个体x和y值.
| 归档时间: |
|
| 查看次数: |
241 次 |
| 最近记录: |