gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:19:02 25 4
gpt4 key购买 nike

这些天我正在阅读有关 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com