Search code examples
javagenericsjavabeans

Can java generic class automatically determing type at instantiation


I have a generic class:

public class ResultCard<T extends Bike>

private T bike;

public ResultCard(T bike)
{
    this.bike = bike;
}

public int someMethod()
{
     bike.showSpeed();
}

Then I have several classes which extend Bike. When I tested out the ResultCard bean I was very surprised that I can instantiate it without specifying the type:

ResultCard resultCard = new ResultCard(bikeType);

and the following call worked:

resultCard.someMethod();

I figured that ResultCard would be instantiated with the Object type as its generic since I didn't specify it when instantiating and then the call to someMethod() would throw a compile time error? But that didn't happen. As if it determines the type from my constructor or something?

Is there anything wrong with not specifying the generic type when instantiating my bean? Am I misunderstanding something?

Thank you.


Solution

  • When you have a generic type parameter with a type bound, as in ResultCard<T extends Bike>, the type parameter is replaced by the bound during compilation. It doesn't matter if you create an instance of a raw type new ResultCard(...) or a parameterized type new ResultCard<SomeBike>(...). After compilation the result will be the same.

    Only if you remove the type bound, the type parameter will be replaced by Object as you expected.