-1

So in Java, I am confused about this for a long time. When I need an instance in another instance, I have 2 ways:

1.Claim variable a as a member variable, and then instantiate it in constructor: (which is a normal way to do that)

public class ClassA {
    SomeType a;
    ClassA(){
         a = new SomeType();
    }
}

2.Directly instantiate it in the member variable definition

public class ClassA {
    SomeType a = new SomeType();
}

So is the second one feasible, and why or why not?

SimZhou
  • 466
  • 1
  • 7
  • 14
  • if you look at the byte-code, it is the same thing – Eugene Mar 22 '21 at 01:37
  • It is a matter of preference, but if you don't mind me imposing my opinions here, I would avoid method 2 at all costs. It's just confusing when you look at the code, because it isn't clear which variables are initialized first. Then you have to go Google it, find the page that tells you the instance variables are initialized before the constructor is run, and then you have to go back and figure out what that means for your code. It's definitely not self-documenting code. I would **always** initialize **all** instance variables in the constructor. – Charlie Armstrong Mar 22 '21 at 01:48
  • Does this answer your question? [Default constructor vs. inline field initialization](https://stackoverflow.com/questions/4916735/default-constructor-vs-inline-field-initialization) – Savior Mar 22 '21 at 02:28
  • They are both feasible ... in the plain English sense of that word. – Stephen C Mar 22 '21 at 02:32

1 Answers1

0

They both represent the same thing. In both your examples, a is assigned during the construction of ClassA, regardless of whether the logic is explicitly in the constructor.

Behind the scenes they then eventually compile to the same code and as @Eugene said, the bytecode is identical.


In terms of preference, you should choose the approach that makes the most sense for you and for others reading your work, there isn't a right answer. However personally I think that the first approach is overly-complex (in your simple example at least).

Henry Twist
  • 5,666
  • 3
  • 19
  • 44