Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a final instance variable has been initialized

Tags:

java

I am still learning Java but I am not sure why this is causing compile time error:

public class AnswerRepository implements IAnswerRepository
{
    private final static SQLiteDatabase database;

    public AnswerRepository(Activity activity)
    {
        if(database != null)
        {
            database = DbOpenHelper.getInstance(activity);
        }
    }
}

I am just trying to check if a final variable has been assigned first before assigning a value to it. But it seems compile time checking doesn't like it. Why is that?

enter image description here

like image 987
Tarik Avatar asked Jan 27 '26 02:01

Tarik


1 Answers

final variables can only be initialized once. Normally, they must be initialized in the constructor, but if they are static, then they need to be initialized when they are defined, like this:

private final static SQLiteDatabase database = new SQLiteDatabase(...);

or, you can initialize it later:

private static SQLiteDatabase database;

static variables will be initialized before object constructors are called. So in this case, database will always be null and since it is null, re-initializing it in the object constructor will cause a compile time error.

like image 163
Cory Kendall Avatar answered Jan 29 '26 15:01

Cory Kendall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!