I am a C# developer and I am highly habituated to initialize a variable in the same declaration statement as
ClassA myClass = new ClassA();
To my point of view, this practice is concise, more readable and looks neat.
Now, I am learning java for android. So far whatever java snippet I am facing, everywhere I see that the snippet writer is using code like this:
ClassA myClass;
myClass = new ClassA();
Now, I understand that, my question may sound silly, but really curious to know, is there any impact / effect or is there any difference between these 2 approach ? I mean, if I compile a code in java like this :
ClassA myClass = new ClassA();
is there anything about it that matters internally ? I just want to be sure that I am not doing anything wrong.
No, this isn't a C#/Java difference, and your habit is appropriate. There's simply no good reason to split declaration and initialization unless you have to due to the initialization being conditional (if/else).
I'm sure there's plenty of Android code which is written appropriately, just as there's plenty of bad C# out there. It sounds like you're just getting unlucky (or perhaps reading lots of code by the same author, who has an unfortunate style).
Both approaches are valid and nobody can stop to initialize the variable at the time of construction.
In 2nd approach you construct the object on demand when you need it .
If you have parametrized constructor .
ClassA myClass = new ClassA(xyz);
In above approach your creating reference with default object.
ClassA myClass;
// some condition
myClass=new ClassA(abc);
// some other
myClass=new ClassA(xyz);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With