Eclipse suggests Null Pointer exception, though I believe I initialized my object

后端 未结 3 1917
臣服心动
臣服心动 2020-12-22 03:14

As the title says I have NPE error. It happens on line:

while (getWidth() > bowl.getX()+10) {

If I remove it, it shows it happens on nex

相关标签:
3条回答
  • 2020-12-22 03:47

    The line:

    GOval bowl = new GOval(10,10);
    

    is declaring a new GOval and hiding the global GOval defined at the bottom.

    That line should just be:

    bowl = new GOval(10,10);
    
    0 讨论(0)
  • 2020-12-22 04:03

    You are shadowing your bowl field at the class level in the init method,

    private GOval bowl; 
    
    public void init() {
      // GOval bowl = new GOval(10,10);
      bowl = new GOval(10,10);
      add(bowl);
      addMouseListeners();
    }
    
    0 讨论(0)
  • 2020-12-22 04:04

    Like most people already mentioned you are shadowing your bowl variable.

    GOval bowl = new GOval(10,10);
    

    should be replaced with

    bowl = new GOval(10,10);
    

    You can configure eclipse that he gives you a warning when you are doing this. In the preferences you have a dedicated part for this under java -> compiler -> errors/warnings

    0 讨论(0)
提交回复
热议问题