-1
public class MainActivity extends AppCompatActivity {     
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button play = (Button)findViewById(R.id.playButton);
        MediaPlayer mediaN = MediaPlayer.create(this, R.raw.master6);
        play.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                mediaN.start();
            }
        });
    }
}

In the above code, I have intialised a new MediaPlayer object within the onCreate method. When i want to use the MediaPlayer object mediaN to call start() method, it asks me to declare the object as final. However, I don't get any errors if I initialise MediaPlayer object as instance variable of the class MainActivity. Why am I asked to make the MediaPlayer object as final when it is declared as a local variable to onCreate method?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Nitish P
  • 1
  • 1

1 Answers1

0

Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren’t final then the copy of the variable in the method could change, while the copy in the local class didn’t, so they’d be out of sync. “Anonymous classes in Java and final variables” https://medium.com/@emerino/anonymous-classes-in-java-and-final-variables-1b1830ac480b This should help.

Bissi singh
  • 50
  • 1
  • 11