What new is being done first - in the constructor or out?

If I define the class as follows:

 public class myClass {
     private x = new anotherClass ();
     private y;

     public myClass () {
         y = new anotherClass ();
     } 
 }

which variable will get the instance earlier? x or y?

And is it really not recommended to assign a variable outside the constructor?

+3
source share
3 answers

Order of execution:

  • Superclass constructor (or related constructor with the same class)
  • Instance variable initializers (expression that assigns x to your code)
  • Constructor body (operator assigning y in your code)

Section 12.5 of the Java Language Specifications contains information.

Regardless of whether you assign a variable in the constructor or not, it is up to you. I really like the rule in which, if the initial value does not depend on any constructor parameters and will always be the same for all constructors, use a variable initializer. Otherwise, assign it in the constructor.

+16
source

Your variables in your code are of types no , but x is created first before calling the constructor. (Do a null check for x on the constructor to find out).

As for the recommendation, it is up to you. One thing, for example. in JavaBeans, since I usually don’t write a standard default constructor (without arguments), I usually initialize some fields in the declaration (if they are necessary so that they are not empty). Otherwise, I will create them in the constructor.

0
source

I recommend that you test, and not just get an answer from someone else:

Make the constructor anotherClass print the line that passed through.

 public class myClass { private anotherClass x = new anotherClass("outside constructor"); private anotherClass y; public myClass() { y = new anotherClass("inside constructor"); } } 

And then you can tell us!

0
source

All Articles