带有覆盖方法的NullPointerException [英] NullPointerException with an override method

查看:153
本文介绍了带有覆盖方法的NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以就解决以下问题的最佳方法发表意见吗?我已尝试使用init块并在构造函数中初始化字段,但在重写方法尝试清除它之前都没有调用。

Can anyone comment with their opinion on the best way to resolve the following issue? I've tried init blocks and initializing the field in the constructor, but neither get called before the overridden method tries to clear it.

 class TestRunner {
        public static void main(String[] args) {
            ftw ftw = new ftw();
            ftw.dontPanic();
        }
    }

    class wtf {

        wtf(){
            this.dontPanic();
        }

        void dontPanic() {
            System.out.println("super don't panic");
        }
    }

    class ftw extends wtf {
        final HashSet variableOfDoom = new HashSet();

        ftw(){
            super();
        }

        void dontPanic() {
            super.dontPanic();
            System.out.println("sub don't panic");
            variableOfDoom.clear(); //This line prints a null pointer exception, because the field hasn't been intialized yet.
        }
    }


推荐答案

这这就是为什么他们建议你不要在构造函数中调用非 final 方法。 私人方法也是安全的,因为它们无法被覆盖。

This is why they recommend you don't call non-final methods from inside a constructor. private methods are also safe, since they can't be overriden.

假设你无法遵循声音建议,出于某种原因,这里有一些其他可能有帮助的观察结果:

Assuming that you can't follow that sound advice, for some reason, here are some other observations that might help:


  • 我假设您为了示例而进行了简化,但是对 .clear()的调用并没有真正完成示例中的任何内容;你也许可以删除它。

  • 很难说没有看到实际的程序,但是你可以通过为变量分配一个新的<$ c $来滑冰c> HashSet 而不是调用 .clear()

  • I'm assuming you simplified for the sake of the example, but the call to .clear() doesn't really accomplish anything in the example; you may be able to just delete it.
  • It's tough to say without seeing the actual program in total, but you may be able to skate by with assigning the variable a new HashSet instead of invoking .clear().

这篇关于带有覆盖方法的NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆