Re: How to solve the error "The local variable may not have been instantiated"?



Hi Shawn,

Shawn wrote:
Hi,

I found an error very annoying. I am hoping someone can give me some suggestion.


public MyClass getMyClass
{
MyClass myClass = null;
^^^^^^^
If you do not forget this assignment, it works perfectly!

if (....) //user clicks the button
{
myClass = new MyClass(..); //myClass object created here
}
else //user clicks the Cancel button
{
System.out.println("User has cancelled the command");
}

return myClass;
}

On the other hand, this...

public MyClass getMyClass
{
MyClass myClass = null;

if (....) //user clicks the button
{
myClass = new MyClass(..); //myClass object created here
...
return myClass;
}
else //user clicks the Cancel button
{
System.out.println("User has cancelled the command");
return null;
}
}

....can be done even simpler:

public MyClass getMyClass
{
if (....) //user clicks the button
{
return new MyClass(..); //myClass object created here
}
else //user clicks the Cancel button
{
System.out.println("User has cancelled the command");
return null;
}
}

And I would prefer this solution!

It ends up with two returns, which I don't like.

Why?

> I don't understand why
I cannot pass with the first code.

Well, it can!

Ciao,
Ingo

.