0

Assuming we have a defined class named Body and we want to create an instance of that class, what is the difference between the two following declarations:

Body a1;
Body a1 = new Body();
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Pape Sow Traore
  • 179
  • 1
  • 3
  • 14
  • mhmm... what do you think? – Ousmane D. Mar 14 '18 at 20:47
  • First one is just a null object referring to nothing. No memory allocated, cannot be used. Second one is an actual Body object with memory allocated. – SomeDude Mar 14 '18 at 20:48
  • The first one only reserves memory needed to store 1 instance of `Body` object. That way you declare a variable `a1`, but you do not initialize it, it does not hold any value. The second one both declares and initializes a variable `a1` of typewhich is an instance if class `Body`. – Urke Mar 14 '18 at 20:52
  • Both are declarations, the second one is additional an initialisation, and thereby as a whole a definition. Try to use the second pattern where ever possible (RAOI:=resource allocation on initialisation)- sometimes it isn't possible, because you can only initialize it in a loop, and have to use it later outside the loop. But don't move all declaration to the top, where forgotten variables from former times try to live forever. Keep the scope of your variables small. It simplifies studying the code. – user unknown Mar 14 '18 at 20:52

0 Answers0