D
D
devpy142021-06-03 05:19:48
Java
devpy14, 2021-06-03 05:19:48

How does the following code snippet work?

How does a piece of code in curly braces work?

public class CarService {

    // car storage
    List<Car> cars = new ArrayList<>();

    // cars in our dealership
    {
        cars.add(new Car(Mark.BMW, Model.I4, 2021, 3_000_000L));
        cars.add(new Car(Mark.TOYOTA, Model.CAMRY, 2011, 10_000_000L));
        cars.add(new Car( Mark.AUDI, Model.A5, 2007, 5_000_000L));
        cars.add(new Car(Mark.AUDI, Model.A5, 2007, 5_000_000L));
        cars.add(new Car( Mark.AUDI, Model.A5, 2007, 5_000_000L));
        cars.add(new Car( Mark.FORD, Model.MUSTANG, 1994, 7_000_000L));
    }


Further in this class, methods for working with the 'cars' sheet are defined, the main method is in another class. Do I understand correctly that cars are added to the collection when an instance of this class is created? That is, is it something like a constructor?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-06-03
@devpy14

This is called an " initialization block ".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question