简体   繁体   English

在Eclipse中调试具有相同名称的多个变量

[英]Debugging multiple variables with same name in Eclipse

I got a null pointer exception when referencing position. 引用位置时我得到一个空指针异常。 In the debug view i found 2 different variables with the same name. 在调试视图中,我找到了2个具有相同名称的不同变量。 One seems to be null and has a green circle, one is the correct variable and has a blue triangle next to it. 一个似乎是null并且有一个绿色圆圈,一个是正确的变量并且旁边有一个蓝色三角形。

我的调试器的视图

Why is my code referencing the null variable and why would there be 2 copies of that variable in memory? 为什么我的代码引用了null变量,为什么在内存中会有2个该变量的副本?

The position gets set in the constructor here 该位置在此处的构造函数中设置

public Obstacle(int x, int y) {
  position = new PVector(x,y);

}

The constructor gets called from a level generator class here 构造函数在此处从级别生成器类调用

obstacle1 = new Obstacle(levelWidth/4, 375);
obstacle2 = new Obstacle(levelWidth/2, 375);
obstacle3 = new Obstacle(levelWidth*3/4, 375);

Not sure what other code to show. 不确定要显示的其他代码。

Green circle indicates a public method 绿色圆圈表示公共方法

Red square indicates a private method 红色方块表示私有方法

Yellow diamond indicates a protected method 黄色菱形表示受保护的方法

Blue triangle indicates default (package visible) method 蓝色三角形表示默认(包可见)方法

You can see the difference between these two icons in What do the icons for methods in Eclipse mean? 你可以看到这两个图标之间的差异在Eclipse中的方法图标是什么意思?

The problem is that you have the field point both in the superclass and the subclass. 问题是你在超类和子类中都有字段point Most likely you are setting the field of the superclass correctly but "forget" to set the field of the subclass. 您很可能正确设置了超类的字段,但“忘记”设置子类的字段。 Consider following example: 考虑以下示例:

class Super {
    Boolean exist;
}

class Sub extends Super {
    Boolean exist;
    Sub() {
        super.exist = true;
    }
}

when you execute following code:: 当你执行以下代码::

Sub sub = new Sub();
System.out.println(sub.exist);

null will be printed because its exist field of Sub has not been initiated. 将打印null,因为尚未启动其existSub字段。

To prevent such errors in the future, do not use duplicated fields in subclasses and use getter methods to access the field values. 为了防止将来出现此类错误,请不要在子类中使用重复字段,并使用getter方法访问字段值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM