A
A
Alexander Vasilenko2015-12-31 07:42:03
Java
Alexander Vasilenko, 2015-12-31 07:42:03

Why shouldn't you call methods in a constructor?

Hey!
I heard many times that it is not recommended to call class methods in the constructor. But why?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Mozhaykin, 2015-12-31
@SanchelliosProg

In fact, only virtual methods should not be called. Because if the inheritor class overrides it, then a situation will arise when the method works before the constructor of the inheritor class is called. And if any fields of the derived class are used in this method, they may not yet be initialized.
And since in Java
then you should not call any public non-final methods in the constructor.
Below is C# code (because I work mainly with this language) illustrating this.

void Main()
{
  new B("name");
}

class A
{
    public A()
  {
       Method();
  }
  
  protected virtual void Method()
  {
  }
}

class B : A
{
    private string Property { get; set; }
  
  public B(string value)
  {
      Property = value;
  }
  
    protected override void Method()
  {
      Console.WriteLine(Property.Length);
  }
}

Result: Object reference not set to an instance of an object.
StackTrace
at UserQuery.B.Method()
at UserQuery.A..ctor()
at UserQuery.B..ctor(String value)
at UserQuery.Main()

P
protven, 2015-12-31
@protven

Well, for example, because at the moment the constructor is called, the object of your class has not yet been completely created (suddenly!). And it's just in the making. Therefore, an object may be in an inconsistent state at the time its method is called.

E
Evhen, 2015-12-31
@EugeneP2

Why not? very possible, only this method must be private . It is not recommended to call public and protected methods. If the class is not final, public methods can be overridden in a subclass, and then your constructor will not call your methods, but overridden ones, which can break the logic of your class and lead to an error.

S
sivabur, 2015-12-31
@sivabur

The first job of a constructor is to put the object's fields into a valid state.
The second task is to simplify the use of the object.
For example, a class constructor for working with a file
And why not call some additional methods to read from a file or validate data. Etc.
A current as already told already it is impossible to cause virtual methods.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question