可以在超级构造函数完成之前初始化java子类的private final字段吗? [英] Can a java subclass's private final field be initialized before the super constructor completes?

查看:80
本文介绍了可以在超级构造函数完成之前初始化java子类的private final字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一对像这样的班级

public abstract class Class1 {

//...

    public Class1() {
        //...
        function2();
        //...
    }

    protected abstract void function2();

}

public class Class2 implements Class1 {

    private final OnSomethingListener mOnSomethingListener = new OnSomethingListener() {
        @Override
        onSomething() {
            doThatOtherThing();
        }
    }

    protected void function2() {
        //uses mOnSomethingListener
        //however mOnSomethingListener is null when this function is called from super()
        //...
    }

    public Class2() {
        super();
    }
}

我假设侦听器为null,因为我正在有效地从 super()引用它,并且尚未实例化.但是,我想使其成为 final ,因为是这样.我能否及时将此字段(侦听器)初始化而无需将其放在超类中(永远不会使用侦听器)?

I assume the listener is null because I am effectively referencing it from super() and it hasn't instantiated yet. However, I want to make it final because, well, it is. Can I get this field (the listener) to initialize in time without putting it in the superclass (which won't be using the listener, ever)?

推荐答案

您的设计是泄漏的 this 问题"的实例,并且是Java中的反模式.永远不要从构造函数中调用可公开重写的方法.

Your design is an instance of the "leaked this problem" and is an anti-pattern in Java. You should never call out to a publicly overridable method from a constructor.

这篇关于可以在超级构造函数完成之前初始化java子类的private final字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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