final field may not have been initialized

T

Timo Nentwig

public class Blah
{
private static Blah singleton;

public static Blah getInstance()
{
if (singleton == null)
singleton = new Logfile();

return singleton;
}
}

Why can't I declare singleton as static final?
 
V

VisionSet

Timo Nentwig said:
public class Blah
{
private static Blah singleton;

public static Blah getInstance()
{
if (singleton == null)
singleton = new Logfile();

return singleton;
}
}

Why can't I declare singleton as static final?

A final variable must either be initialised at the point of declaration, or
at the very least the compiler must be convinced they will be initialised
before there is any possibility they may be used.

so with static either:

class Mine {

static final Object obj1 = new Object();

// or

static final Object obj2;

{obj2 = new Object();}

// or

final Object obj3;

Mine() {
obj3 = new Object();
}
}



since in all cases the Objects must be initialised before they are used.

You cannot initialise a final attribute in a method, since other methods
that use that variable maybe called beforehand.

Therefore you cannot have the lasy behaviour you are after with a final
attribute.

You must do:

private static final Blah singleton = new Logfile();
 
T

Tor Iver Wilhelmsen

Timo Nentwig said:
private static Blah singleton;

Are you sure there isn't a "final" there you've forgotten to tell us?
That's the only way you could have gotten that error message.
if (singleton == null)

Here you use the variable before it's been assigned to.
Why can't I declare singleton as static final?

You can, but you need to assign to it before anything uses it.
 
?

=?iso-8859-1?Q?Nils_O=2E_Sel=E5sdal?=

public class Blah
{
private static final Blah singleton = new Logfile();

public static Blah getInstance()
{

return singleton;
}
}
Why can't I declare singleton as static final?
Prvoided Logfile is of a Blah type.
 
R

Raymond DeCampo

VisionSet said:
// or

static final Object obj2;

{obj2 = new Object();}

// or

I think you probably meant:

static final Object obj2;

static {obj2 = new Object();}

Also, another way to do the same thing without the static initializer
(which some people either are not comfortable with or do not like
stylistically):

static final Object o = makeObject();

private static Object makeObject()
{
return new Object();
}

Ray
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,836
Latest member
login dogas

Latest Threads

Top