2

How can I change the generic type in child-classes. I know, that i can override method load(); But i want to make the universal method for all children. I have abstract super class

public abstract class Vehicle <T extends Human> {
    T t;
    private final int maxPassengers;
    private Set<T> currentPassengers = new HashSet<>();

    public Vehicle(int maxPassengers) {
       this.maxPassengers = maxPassengers;
    }

    public void load (T human) throws ToManyPassangersExeption {
        if (currentPassengers.size()<maxPassengers)
            currentPassengers.add(human);
        else
            throw new ToManyPassangersExeption();
    }
}

load() realize loading Human to vehicle. I have different types of Human. For example:

public class Policeman extends Human {
    }

In my class PoliceCar, i what to load only Policemen.

public class PoliceCar <T extends Policeman> extends Vehicle {
    T t;

    public PoliceCar() {
        super(5);
    }
}

Using this code, i can load all instanceof Human to PoliceCar.

How can i load only Policeman in PoliceCar without Overriding method load()?

A. Kashnikov
  • 143
  • 2
  • 11

1 Answers1

2

Declare the PoliceCar type with a non-raw superclass:

class PoliceCar<T extends Policeman> extends Vehicle<T>

Then the load method will require a T parameter, where T is a subclass of Policeman.

See What is a raw type and why shouldn't we use it?.

Community
  • 1
  • 1
Andy Turner
  • 137,514
  • 11
  • 162
  • 243