0

I need to make a final string in a class and initialize it from within a method, i searched the internet some says its possible some say not!
i passed over this and in the accepted answer he stated that's possible from constructor said nothing about non-constructor methods

But, if you remove static, you are allowed to do this:

class A  {    
    private final int x;

    public A()
    {
        x = 5;
    } }

in my case in Android i want to do this

public class MyActivity extends Activity
{
    final String DOWNLOADS_FOLDER_PATH;
    @Override
    public void onCreate(Bundle savedInstanceState)
    { ....

   DOWNLOADS_FOLDER_PATH=Environment.getExternalStorageDirectory().getPath()+"/downloads/";
    // i cant do that neither
    // DOWNLOADS_FOLDER_PATH="s";
    }
}

I need to initialize from a method because i have a call to

Environment.getExternalStorageDirectory().getPath()

any idea?

Community
  • 1
  • 1
Ahmad Dwaik 'Warlock'
  • 5,953
  • 5
  • 34
  • 56

4 Answers4

5

Why cant you initialize it immediately? getExternalStorageDirectory is static method, so:

static final String DOWNLOADS_FOLDER_PATH = Environment.getExternalStorageDirectory().getPath() + "/downloads/";
aim
  • 1,461
  • 1
  • 13
  • 26
4

You can't initialize final variables from a method - only constructors and initializer blocks. The reason for this is that the variable MUST NOT change its value throughout the lifetime of the object it belongs to (the meaning behind the 'final' keyword).

Let's analyze the final variable's values over the course of the object creation and usage if you could initialize it with a normal method:

  1. Object is created, final member's value is not initialized, so null;
  2. Constructor returns, the object is used by the rest of the code. The final variable is also used.
  3. You call a method that assigns a value to the final member. The final value effectively changes.
0

You can use constructor as well

public class MyActivity extends Activity
{
    final String DOWNLOADS_FOLDER_PATH;

    // constructor
    MyActivity(){
       super();
       DOWNLOADS_FOLDER_PATH=Environment.getExternalStorageDirectory().getPath()+"/downloads/";
    } 

    @Override
    public void onCreate(Bundle savedInstanceState)
    { ....

    }
}
Rakesh Soni
  • 10,135
  • 5
  • 44
  • 51
0

From JLS:

A final variable may only be assigned to once.

But here if you assign final variable a value in any method other than constructor then it might get re-assigned. That is why assignation of final variable is not allowed in methods except constructor.

Constructor ensures that assignation is done for every new final variable.

Gaurav Gupta
  • 4,586
  • 4
  • 39
  • 72