Your second option is not a valid one and you need to specify the type either in new objecttype() statement or separtely. C heck your code you should find statments like:
Originally posted by Ad Criag: objectname = new objecttype
Sometimes you know that you need a variable for an object of a specific type, but you don't know exactly what that object will be. You might then see code like this:
ClassName myClass; // declares the variable myClass of type ClassName
// other lines....
myClass = new ClassName();
// the above line uses new to allocate a new class of type ClassName, // and assign it's reference to the variable, myClass, whose type is // already known to the compiler because it was declared earlier
---------------------------
Two, use one line to declare the variable AND instantiate the object:
public static void main(String [] args) {
ClassName myClass = new ClassName();
// This performs the same work but does it all in one source line. // The first ClassName tells the compiler the type of the variable // (myClass) the second ClassName tells the compiler what type of // object to instantiate.
--------------------------
I think more a matter of style but then, certain coding standards may specify a preference.
(Edited to add) I had not caught Katrina's post and that is a good example. The dynamics of a particular design may well have you instantiating objects "on the fly" and you may not know what type until that point. So the one liner is a little more "source efficient". So in that case you might choose the one-liner. If you are initializing an environment to a known condition, you may want to declare variables up front and instantiate later. [ June 27, 2007: Message edited by: Bob Ruth ]
------------------------
Bob
SCJP - 86% - June 11, 2009
Originally posted by Remko Strating: I would prefer:
even if I would know the real initialization would be later.
There are cases where this is not possible, though. E.g., the way to get and use a connection in JDBC is like this:
The getConnection call must be inside the "try" block -because it can throw an exception- but "con" must be declared outside of it, because it's needed in the "finally" block.
This is just an example; you'd encounter this whenever an object is needed in the finally block, but must be created or retrieved in the try block.