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

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

    It is probably not a good idea. If you don't make that class final and don't make the setName( ... ) method private or final someone else is able to extend your class and overrid the setName( ... ) method. Your constructor (in your base class) will call that method in the extending class instead of your implementation. Nobody knows what that method can do. As a rule of thumb: a constructor shouldn't call methods that can be overriden

提交回复
热议问题