What really happens (i.e. what the compiler generates from classes) - 1

"Hi, Amigo! Here's some more information for you."

"I already told you that the compiler actually converts all anonymous classes into ordinary inner classes."

"Yep. I even remember that their names are numbers: 1, 2, 3, etc."

"Exactly. But there's another nuance here."

"If a class is declared inside a method and uses any of its variables, then references to those variables will be added to the generated class. See for yourself."

"We start with this:"

Before compiling:
class Car
{
 public ArrayList createPoliceCars(int count)
 {
  ArrayList result = new ArrayList();

  for(int i = 0; i < count; i++)
  {
 final int number = i;
   result.add(new Car()
    {
     public String toString()
     {
      return ""+number;
     }
    });
  }
  return result;
 }
}

"And the compiler generates this:

After compiling:
class Car
{
 public ArrayList createPoliceCars(int count)
 {
  ArrayList result = new ArrayList();

  for(int i = 0; i < count; i++)
  {
   final int number = i;
   result.add(new Anonymous2 (number));
  }
   return result;
  }

 class Anonymous2
 {
  final int number;
  Anonymous2(int number)
 {
  this.number = number;
 }

  public String toString()
  {
   return ""+ number;
  }
 }
}

"Did you get the point? The inner class can't change the method's local variable, because by the time the inner class's code is executed, we may be exiting the method altogether."

"Now the second point. The toString() method uses a passed variable. To accomplish this, it was necessary to:"

A) save it inside the generated class

B) add it to the constructor.

"Got it. Classes declared inside methods always use copies of variables."

"Exactly!"

"Then it makes sense why variables must be final. And why they can't be changed. If you're actually working with copies rather than the originals, the user won't understand why he can't change variables' values, which means we need to just forbid him from changing them."

"Right, declaring variables as final seems a small price to pay in exchange for having the compiler generate a class for you, pass it to the method, and save all of the method's variables that you want to use."

"I agree. Anonymous local classes are still super cool."

"If I declare a local class inside a method, and I use the method's variables in it, will the compiler add them to the class too?"

"Yes, it will add them to the class and its constructor."

"That's what I thought."