Search code examples
javatype-conversionjvm-hotspothungarian-notation

Is there any performance decrease in java, for extending classes for "no" reason?


I have a Vector3i class that is useful in a lot of situations, but I've found myself extending it to use the type system to prevent bugs.

For example, I might have an "ego-centric" vector3i that is local to an object in the world, and a world co-ordinate vector3i.

The two are naturally incompatible without conversion and are meaningless to each other.

It would be a good situation to use True Hungarian Notation but instead I'm extending the class and adding no new functionality.

Am I incurring a performance loss considering the JVM/Hotspots optimizations?


Solution

  • Inheritance is a powerful tool, but the power comes at a price. Inheritance has a lot of pitfalls and problems of its own. In particular, it breaks encapsulation and can lead to fragile code when not implemented with care.

    The inheritance mechanism in Java has been developed continuously for over 15 years. You can rely on it to be fast and efficient. There are no significant performance-related reasons to pass on inheritance when it your data model calls for it.

    For your case, it may make more sense to represent your functionalities by composition rather than by inheritance (in other words, instead of having ClassB extend ClassA, make ClassA an instance field within ClassB and then delegate method calls to the encapsulated object). You should at least consider it. Compared to inheritance, composition results in code that is more robust, and less fragile.