Desire to initialize an element before passing it to the parent constructor

Here's an example of my puzzle toys:

public abstract class Car {
    public Car(Seat[] seatsParam) {    // Could be protected.
        driverSeat = new DriverSeat();
        seats = new ArrayList<Seat>();
        seats.add(driverSeat);
        seats.addAll(seatsParam);
    }
    private final List<Seat> seats;
    private final DriverSeat driverSeat;
}

public class MyCar extends Car {
    public MyCar() {
        super(new Seat[]{new PassengerSeat()});    // Cannot assign to member.
    }
    public PassengerSeat getPassengerSeat() {  // Would like this accessor.
        return passengerSeat;
    }
    private final PassengerSeat passengerSeat;
}

      

The car has a Seat list (seat supertype), ideally initialized in the constructor. Every car has a DriverSeat. MyCar also has a PassengerSeat that I would like to access from the subtype, but also from the parent list (like Seat).

Some things that I got knocked down:

  • Above code: The passenger will not be initialized in the subclass. I could get the list in MyCar's constructor and downcast, but that's ugly.
  • Becoming a static passenger: it shouldn't be static, as there may be many other MyCars with unique locations.
  • Define that Car defines an abstract getSubclassSeats () to which it adds a driverSeat: this won't work in the constructor, since the userSeat will not be initialized. I could make the places non-final and do it after the constructor, but again, ugly.

What I mean is that this is what I should be able to express in OO, define a variable and pass it to a parent reference. But I cannot think of how to do it. It's been a while since I've been working with C ++, but is this what initialization lists solve? If so, does Java have an equivalent?

+3


source to share


1 answer


I've seen people with similar problems use thread-local variables, and god knows what other terrible tricks, luckily there is a simple solution:



public MyCar() {
    this(new PassengerSeat());   
}

private MyCar(PassengerSeat seat) {
    super(new PassengerSeat[]{seat});   
    // Well do something with your seat now.
}

      

+2


source







All Articles