java - How to achieve type safety with generics? -
I am currently trying to expand a large project. Some things have been given in the project and I have some problems in securing the type of extension.
I will make the example code more common.
Public abstract class garage {public & lt; T car spreads & gt; Zero Parkcars (T ... cars) {// combines cars in a list}}
Abstract class Garage
. Like SportCarGarage
or SUVCarGarage
. Those garages behave differently in some manner but there is definitely park carriage
function in every garage car
in car
There are some different children like SUVire
, they are also given.
Now I want to park only in a SportCarGarage
in SportCars
.
I was hoping this would do something like this:
public-class sportspersons < Expansion of T Sports Car & gt; Expansion of garage {}
...
sportscars & lt; GameCard & gt; SportsGeorge = newportcargage (); // would be great if I & gt; GameCard & gt; SUVAR BMWX 5 = new SUVAR (); Sports car Porsche 9 11 = new sportscar (); SportsCarGarage.parkCars (porsche911); // Works! SportsCarGarage.parkCars (bmwX5); // should not work, but it does: (
I think the syntax is wrong somewhere. But preventing other gods to park cars in the wrong type garage There should be one way, without edit: I think my example is just wrong and this is the reason why it will not work with code. Thanks for the help ... Your type and method in the class In your type, the
parkCars
are different, for this to work, you can expand your interface to
Public Abstract Class Garage
Now your sports cargo
will only accept sports car