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 (); } } 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 (); } } 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.
a must be initialized. Where initialization takes place depends on the specific task / implementation. - RegentSource: https://ru.stackoverflow.com/questions/639779/
All Articles
Bthere 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