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 B is a subtype of A if every function that can be invoked on an object of type A can also be invoked on an object of type B.
  • Inheritance refers to reuse of implementations. A type B inherits from another type A if some functions for B are written in terms of functions of A.

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,

  1. Arrays differ from generic type in two important ways. First arrays are covariant. Generics are invariant.
  2. Covariant simply means if X is subtype of Y then X[] will also be sub type of Y[]. Arrays are covariant As string is subtype of Object so String[] is subtype of Object[]

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



🌱 Back to Garden