为什么从构造函数调用Set方法不是一个好主意? [英] Why it is not a good idea to call Set method from constructor?

查看:339
本文介绍了为什么从构造函数调用Set方法不是一个好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅在继承或大多数情况下才是真实的?

Is it true only in Inheritance or most of the cases ?

public class MyClass {
   public int id;

     public MyClass() {
         // Some stuff 
         setId(5);
     }

     public setId(int id) {
         this.id = id;
     }
}


推荐答案

是非常真实的

因为setter始终是 public 方法。而如果你的类不是 final 那么有外来方法调用的问题。哪个不是线程安全的,即它被称为转义这个引用。所以从一个构造函数,如果你调用一个方法,它应该是 final private 。否则对象的安全初始化不会发生真实系统中的许多错误。

Because setters are always public methods. And if you class is not final then there is issue of alien method call. Which is not thread safe i.e. it is known as escaping of this reference. So from a constructor if you are calling a method it should be final or private. Else safe initialization of object will not happen which cases many bugs in real systems.

除了上述之外,我们应该不要从构造函数调用 public 方法,因为如果该类是为了继承而不是构造函数不能调用可覆盖的方法,直接或间接

Apart from the above we should never call public method from the constructor because if the class is intended for inheritance than 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 be 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.

来源

这篇关于为什么从构造函数调用Set方法不是一个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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