Local classes: classes inside methods - 1

"Hi, Amigo!"

"Another little tiny topic is local classes."

"As you have seen, you can create classes not only in separate files, but also inside other classes. But that's not all. Classes can also be created within methods. These classes are called local classes. They work like ordinary inner classes, but they can be used within the methods they are declared in."

"Look at the screen:"

Example
class Car
{
 public ArrayListcreatePoliceCars(int count)
 {
  ArrayList result = new ArrayList();

  class PoliceCar extends Car
  {
   int policeNumber;
   PoliceCar(int policeNumber)
  {
   this.policeNumber = policeNumber;
  }
 }

 for(int i = 0; i < count; i++)
     result.add(new PoliceCar(i));
  return result;
 }
}

"And why do we need such classes?"

"Putting a class, with all of its constructors and methods, inside a method doesn't make for very readable code, don't you think?"

"Exactly. You're absolutely right."

"You can also use anonymous inner classes inside methods. But these classes do have one small advantage, and consequently, they are used inside methods quite often."

"A class declared within a method can use that method's local variables:"

class Car
{
 public ArrayListcreatePoliceCars(int count)
 {
  ArrayList result = new ArrayList();

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

"But there is one limitation: the variables are «read-only»—they can't be changed."

"Here is why that restriction exists:"

"Classes declared within a method can only access a method's variables that are declared using the keyword final. In the example above, you can see that I can't immediately assign the value of i to policeNumber. Instead, I first save it to the final variable number."

"Being able to use a method's variables is super cool. I hope properly appreciate it. It's too bad you can't change variables though."

"Ellie will explain to you today why you can't change them. Meanwhile, I'm going to go take a nap for about an hour."

"Good night, Kim. Thanks for the interesting lesson."