Class fields are represented by object references. Question: Should a default constructor allocate memory for fields-references?

Example:

class A {} class B { A a; B() { a = new A (); } } 
  • reformulate the question, in this form it is not very clear what you want to know - Artem Konovalov
  • @ArtemKonovalov, reformulated - studentST
  • one
    And what is the default constructor in question? In a? For in B there is no default constructor. In general, in general: if you need, then initialize the field in the constructor. Do not need - do not initialize. When using DI, B(A a) { this.a = a; } B(A a) { this.a = a; } . - Regent
  • If you need to initialize an object in the constructor, then yes. It all depends on the task. - androschuk
  • one
    @studentST tasks are different. In some classes, you need to initialize something in the constructors, in others - not. There are no universal solutions. - Regent

1 answer 1

Usually in java they don’t talk about allocating / freeing memory.

If the question is whether member fields need to be initialized before use, yes.

  class A {int v = 5;} class B { A a; // a == null B() { } void foo() { System.out.print(av); // Может вызывать NullPointerException } void bar() { if (a == null) a = new A(); System.out.print(av); // ok } } //// B b = new B(); b.foo(); // NullPointerException - ba не инициализирована b.bar(); // ok b.foo(); // ok, ведь a уже инициализирован 

Using the example of the method bar showed that it is not necessary to do this in the constructor

A good thing is the lack of methods in the public interface that allow inconsistent (use of uninitialized variables) class state.

  • @Victor, I wrote "before use". In the first edition of this was not, yes - vp_arth
  • @vp_arth, i.e. if there is a field in the class that references another class - would you kindly allocate memory in the constructor without parameters? - studentST
  • four
    @studentST is not, the answer about this is not said, and in general it is not. Why, by the way, you so select exactly the designer without parameters? It is also not clear. The idea is the same for all designers. Before using, a must be initialized. Where initialization takes place depends on the specific task / implementation. - Regent
  • @studentST is not. If there is a field, then it is necessary to initialize it, and no matter where in the constructor or before use - JVic
  • I think the first call to trycatch should not be wrapped =) Clearly, no? - vp_arth