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

前端 未结 6 1385
梦毁少年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:53

    The constructor constructs the object and you should only call things that you know work in the 'not fully constructed state'. In your example the SetId does nothing other that set a value so it's fine. However if SetId used other state/infothat wasn't ready yet then you could run into an issue.

    It's not a commandment - rather it's a 'be wary of what you do'

提交回复
热议问题