Skip to content
Advertisement

Is there any benefits of using generic parameter rather than using the base class parameter?

Please review the code below:

JavaScript

What’s the difference between draw1() and draw2()? Which one is better? Does draw2() have more extensibility? Or does draw2() have better performance?

Advertisement

Answer

There is no difference in your scenario, because the type of the object being drawn is consumed internally in the drawX method.

It would make a difference if your method were to use T in some other context, such as returning the original back to the caller:

JavaScript

This makes a difference in situations when a subclass defines new methods on top of the base class. For example, if Circle defined

JavaScript

you could do the following:

JavaScript

This would be impossible with an implementation returning Shape.

Note: The above is to demonstrate the differences, not to suggest that the new implementation is more desirable than the original one.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement