简体   繁体   中英

How do I create multiple abstract instances using a counter?

Here is my code:

for (int i = 0; i < 40; i++)
{
     Button btn = new Button()
     {
         @Override
         public void click()
         {
             result = i;
         }
     };
     btn.setLocation(i * 30, 0);
     btn.setLabel("Option " + i);
}

However, since my button class is abstract, int i cannot be used because it is not listed as final . How do I enable the use of a counter in this scenario?

Thanks.

You can create a final variable from the non-final one:

for (int i = 0; i < 40; i++) {
  final int i0 = i;
  //etc. 

Note that with Java 8+ the final modifier is optional.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM