Why it is not a good idea to call Set method from constructor?

前端 未结 6 1391
梦毁少年i
梦毁少年i 2020-12-18 09:57

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

public class MyClass {
   public int id;

     public MyClass() {
         // Some stuff 
         setI         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-18 10:35

    Since in Java, all functions are virtual by default, unsealed method calls in the ctor are risky for reasons explained in this thread.

    That's why you might want to make either SetId or MyClass final or private.

提交回复
热议问题