https://www.youtube.com/watch?v=3-d0OJeaez0
Method calls on arbitrary objects can be slow. This is because, due to subtyping, in some situations there is no way to know where the method will be in the table, and a binary search has to be done.
The difference between subtyping and inheritance in OO
In the object-oriented framework, inheritance is usually presented as a feature that goes hand in hand with subtyping when one organizes abstract datatypes in a hierarchy of classes. However, the two are orthogonal ideas?
- Subtyping refers to compatibility of interfaces. A type
Bis a subtype ofAif every function that can be invoked on an object of typeAcan also be invoked on an object of typeB. - Inheritance refers to reuse of implementations. A type
Binherits from another typeAif some functions forBare written in terms of functions ofA.
https://www.cmi.ac.in/~madhavan/courses/pl2006/lecturenotes/lecture-notes/node28.html
Covariance / Invariance
Many programming language type systems support subtyping. For instance, if the type Cat is a subtype of Animal, then an expression of type Cat should be substitutable wherever an expression of type Animal is used.
Variance refers to how subtyping between more complex types relates to subtyping between their components. For example, how should a list of Cats relate to a list of Animals? Or how should a function that returns Cat relate to a function that returns Animal?
Depending on the variance of the type constructor, the subtyping relation of the simple types may be either preserved, reversed, or ignored for the respective complex types.
THE JAVA PROBLEM
From Effective Java by Joshua Bloch,
- Arrays differ from generic type in two important ways. First arrays are covariant. Generics are invariant.
- Covariant simply means if
Xis subtype ofYthenX[]will also be sub type ofY[]. Arrays are covariant As string is subtype of Object soString[]is subtype ofObject[]
Invariant simply means irrespective of X being subtype of Y or not , List<X> will not be subType of List<Y>.
https://stackoverflow.com/questions/18666710/why-are-arrays-covariant-but-generics-are-invariant
For example: In Java every class is a subclass of Object (even Types). As a consequence, this code compiles perfectly fine:
String [] a ={"Hello"};
Object [] b= a;
b[0] = false;
String s = a[0];
System.out.println(s);Compiler does not produces any warning about the above code, but when you try to run, it throws an exception.
if you are not that experienced with Java then avoid arrays and use generic Lists since the compiler will stop you adding the wrong thing to the List. If you really want to use Arrays then you just need to be very careful that you protect those arrays ie. don’t return them from methods otherwise you run the risk of someone adding the wrong thing which might not manifest until runtime