heyNow
heyNow

Reputation: 886

override tostring of anonymous class

I want to override the title of each movie in a list.
I tried to make the x static and final but the compiler complains.

List<Movie> mList = new ArrayList<Movie>();

for(int i = 0; i < 5; i++)
{
int x;
mList.add(new Movie(){


  toString(){

   // need an easy way to give a unique string to each movie here.
   return "Movie" + x;
  } 
}
}

Upvotes: 2

Views: 1362

Answers (1)

arshajii
arshajii

Reputation: 129547

This should work:

List<Movie> mList = new ArrayList<Movie>();

for (int i = 0 ; i < 5 ; i++) {
    final int x = i;  // or anything else, but you must assign it some value
    mList.add(new Movie() {
        @Override
        public String toString(){
            return "Movie" + x;
        } 
    });
}

You cannot make x static - the static modifier is used only on the data fields (or methods) of a class. Furthermore x must indeed be final so as to allow the toString method of the anonymous class to access it.

Upvotes: 6

Related Questions