You are creating the instance the "wrong way"
You are not creating an instance of your generic class, so the compiler is accepting a different type in the constructor without error.
This way you've created an instance of your class:
Grid<Empresa> grid = new Grid(...);
is allowed by the compiler because of backward compatibility. See: The Java Tutorials - Raw Types .
In short, although you have no class Grid
because what you declared was Grid<T>
, that is, a generic , the compiler considers that there is a class Grid
and he calls it raw type . It needs this for compatibility with old code, prior to the advent of generics
However, the way to create an instance of a generic class is this:
Grid<Empresa> grid = new Grid<Empresa>(...);
That is, you should enter the generic parameter when creating the instance , otherwise you are actually creating an instance of raw type and not an instance of your generic class.
If you correctly create an instance of the generic class you will get a compile error when the type passed to your constructor does not hit the generic parameter type.
In C # (other language to support generics ) does not have such a raw type so you are required to explicitly < in> generic parameter as I did above.
In Java you can also use the diamond > syntax, letting the compiler break the generic parameter type from the variable declaration: / p>
Grid<Empresa> grid = new Grid<>(...);
If you follow this practice by explicitly specifying the generic parameter or using diamond syntax, a compile error will be generated if you attempt to use an instance of type incompatible with generic parameter informed.
Why does NetBeans not alert to bad practice?
Because the warning of the compiler regarding the use of raw types is turned off by default. If you look at the hints of the compiler, however, the warning will be there:
Note: Main.java uses unchecked or unsafe operations.
If you enable this warning in NetBeans (in Eclipse it is enabled by default), you will be warned by the editor and also during compilation with the following message:
Grid is a raw type. References to generic type Grid
should be parameterized.
Type safety: The constructor Grid(Integer, List) belongs to the raw type Grid.
References to generic type Grid should be parameterized.
You could even treat this warning as an error, preventing compilation when an instance of a raw type was created.
I do not have NetBeans installed but this image shows more or less where this setting is: