CodeGym /Courses /Java Multithreading /Local classes: classes inside methods

Local classes: classes inside methods

Java Multithreading
Level 4 , Lesson 5
Available
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."

Comments (11)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
matemate123 Level 50, Kraków, Poland
13 April 2023
"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." Tell me whether I understood corectly. In first example we have inner nested class PoliceCar and we can use (not final) int i when we creating Police Cars. And in second example we have annymous inner class which is subclass of Car and now we have one more restriction because we can use only final variables? It's that difference?
Andrei Level 41
8 April 2021
I have a question, here: How do I access the police number variable of each cars from the list? I have written the code below but I can't see to find a way to access that variable.

public class Car {

        public List<Car> 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;
        }

    public static void main(String[] args) {
            Car policeCar = new Car();
            ArrayList<Car> policeCars = new ArrayList<>(policeCar.ArrayListcreatePoliceCars(5));

            for (int i = 0; i < policeCars.size(); i++){
                System.out.println(policeCars.get(i));
            }
    }
}
Dawid Level 28
17 April 2021
You probably dealt with it already, but if not: 1) policeNumber must be public 2) the code for access would be:

System.out.println(policeCars.get(i).getClass().getField("policeNumber").get(policeCars.get(i)));
Which means you have to use Reflection, which means you should rather avoid this need :)
Andrei Level 41
19 April 2021
Hi, I hadn't found out an answer so thank you! ☺️👍
Vahan Level 41, Tbilisi, Georgia
4 February 2020
And where is the anonymous class there?
Seb Level 41, Crefeld, Germany
6 February 2020
The anonymous class is the red part on lines 10 to 13 - new Car() { int policeNumber = number; } Just like the PoliceCar class in the first example, this anonymous class also extends car and has its own instance variable policeNumber. The difference being that in this case the class is anonymous, thus we neither have a class name nor do we have to explicitly extend Car as this happens automatically.
Vahan Level 41, Tbilisi, Georgia
6 February 2020
Many thanks. In fact, I knew where the anonymous class is located there, but I had some confusion with it and you answered my latent questions very accurately!!!
Fadi Alsaidi Level 34, Carrollton, TX, USA
16 December 2020
Forgive me for being slow, but how in the word would the compiler knew that int PoliceNumber is going to be used in the constructer of the the anonymous class ??? to me we are just adding a variable to anonymous class called PoliceNumber and that's it.
Andrei Level 41
8 April 2021
Let me try to explain: The program is not using the int PoliceNumber in the constructor, because

 result.add(new Car()
  {
   int policeNumber = number;
  });
you are creating a new Car object, not a constructor. And each new car object has a variable policenumber.
Denis Level 25, Vancouver, Canada
28 June 2019
I think there are mistakes in your code. For ex:

public ArrayListcreatePoliceCars(int count)
I think you missed backspace. Otherwise you can't return anything:

return result;
Hashirama Level 26, Port-Harcourt, Nigeria
29 July 2019
Yes, she missed a space, leaving the method without a return type