java - 在构造函数上使用 init() 方法是一种不好的做法吗?

标签 java constructor initialization

这些天我正在阅读有关 Java 的良好实践,并且在某些时候 我的世界已经支离 splinter ,因为他们说调用“init”方法 我知道构造函数可能是一种不好的做法..公共(public)方法可以被覆盖, 但就我而言,情况有点不同,所以请帮助我摆脱它。示例:

    public class MLabel extends JLabel {

    private Color color;

    public MLabel(String txt, Color color, int align) {
        super(txt, null, align);
        this.color = color;
        init(); 
    }

    private void init() {
        setFont(new Font(Font.SERIF, Font.BOLD, 16));
        setForeground(color);
    }

}

I already read that answer, but still couldn't find the solution, think that factories will make a much robust code for this simple task, I just want to "configure" the JLabel for easy usage

thank you all, study about good pratices on programming is a little hard because the problems don't appear with errors but with how it could be made, I've upvoted all for the great answers, and I'll change inits() for factories for now, at least.. thank you

最佳答案

Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will get invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected. To make this concrete, here’s a class that violates this rule:

来源:Effective Java,第二版,第 89 页。

您可以阅读整个讨论以了解为什么不在构造函数中调用 init 方法。使用生命周期钩子(Hook)是个好主意,例如像spring这样的框架就提供了这样的功能。

关于java - 在构造函数上使用 init() 方法是一种不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45926691/

相关文章:

java - Android/Eclipse 在插件中打开 MainActivity 之外的文件

java - 编译 java 文件时遇到问题(ANT 和 XML 相关)

c++ - 使用没有默认构造函数的类/类型初始化自定义容器

java - java中如何强制构造函数使用类自己的方法

python - 将值附加到空列表的最佳实践

java - 匹配器在文本中找不到任何类似于正则表达式模式的内容

c++ - 常量引用包装器

python - python类的奇怪行为

java - Spring单例初始化完成后如何运行方法?

java - 添加自定义 Lint 规则