0

I've made an example of Aggregation in Java, but it didn't work in the final step when I try to add an Object because the compiler indicates null pointer excepction. I suppose that I didn't initialize the object, but I have no idea where I could do it. For example: I create a Car object whit its data and I wanna aggregate it to a Park that has a list of all cars. When I use Parqueo.add(car) it says that "carros" is null.

Main Class

public class main {
    public static void main(String[] args) {

//---First Car---
        Carro car = new Carro();
        car.setMarca("Honda");
        Motor motor = new Motor();
        motor.setChasis("123456fb");
        car.setMotor(motor);

//---Second Car---
        Carro car2 = new Carro();
        car2.setMarca("Toyota");
        Motor motor2 = new Motor();
        motor2.setChasis("3174HM");
        car2.setMotor(motor2);


        System.out.println(car.toString());
        System.out.println(car2.toString());

//---Parqueo----
Parqueo parqueo = new Parqueo();
parqueo.setDireccion("Zona 2");
parqueo.addCarro(car); <--- Error Here
parqueo.addCarro(car2); <-- Error Here

System.out.println(parqueo.toString());

    }
}

Parqueo Class

import java.util.List;

public class Parqueo {
    //Agregación
    //Parqueo lleva rombo
    private String direccion;
    private Carro carro;
    private List<Carro> carros;

    public String getDireccion() {
        return direccion;
    }

    public void setDireccion(String direccion) {
        this.direccion = direccion;
    }

    public List<Carro> getCarros() {
        return carros;
    }

    public void setCarros(List<Carro> carros) {
        this.carros = carros;
    }

    public void addCarro(Carro carro){
        this.carros.add(carro);  //Error Here <------
    }

    @Override
    public String toString() {
        return "Parqueo{" +
                "direccion='" + direccion + '\'' +
                ", carros=" + carros +
                '}';
    }
}

Errors

java.lang.NullPointerException: Cannot invoke "java.util.List.add(Object)" because "this.carros" is null
    at Parqueo.addCarro(Parqueo.java:34)
    at main.main(main.java:25)

0 Answers0