Reputation: 12119
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.
Upvotes: 2
Views: 1098
Reputation: 17940
Not sure what snippets you looked at but there is nothing preventing you to do :
ClassA myClass = new ClassA();
The difference is that java won't allow you to ignore exceptions as C# would so in a lot of cases you have something like this:
try{
ClassA myClass = new ClassA();
}
catch(Exception e)
{
}
In that case, if you like to use the myClass variable outside of the try block, you'll have to define it outside the try block and initialize it in the try:
ClassA myClass = null;
try{
myClass = new ClassA();
}
catch(Exception e)
{
}
if(myClass != null){
myClass.doSomething();
}
Upvotes: 1
Reputation: 7899
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);
Upvotes: 1
Reputation: 5709
The only "difference" it may make is when your myClass is used in try-catch blocks.
ClassA myClass;
try {
myClass = new ClassA(); // exception may occur here
} catch {
// catch and process exception
} finally {
// always do something
}
doSomethingWith(myClass);
If you declare and initialize in try block, then it won't be visible outside of it.
That's the only reason for doing so, from my POV, ATM.
Upvotes: 0
Reputation: 5246
ClassA myClass;
At this point, it wont create a new java object until you call "new" keyword. But the point is, if your variable is global dont use direct declaration.
Upvotes: 0
Reputation: 1503839
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).
Upvotes: 7