Search code examples
javavirtual-functionsoverridingliskov-substitution-principlemethod-hiding

How Liskov's Principle of substitution is related to overriding in JAVA? What is different between complete hinding and overriding?


In programming language, if you want that a child object should act as a substitute to parent & still it should not loose its own identity (of being child), you must have parent's permission. And that is why we make such methods virtual in C# or C++. And this becomes a complete hiding. Is the complete hiding considered as overriding in java? 99% of time I have wrong concept here because I think I am considering it only hiding. Can an overriden function be a complete hiding as fas as only JAVA is concerned?


Solution

  • Liskkiov's principle of substitution is linked to a function returning an abstract parent implementation instead of concrete child implementation. For example

    ArrayList getList vs List getList
    

    In the above example in the first case the getList method returns a concrete List implementation and in the second case the getList method returns an instance of the List interface. Now as per Liskov principle of substitution the second approach should be used as the second method can be overriden by subclasses to return different concrete implementations of List while in the first instance only an ArrayList of sub classes of ArrayList can be returned. So the first case is less abstract than the second case and as per Liskov's substitution principle the parent implementation should be as abstract as possible to allow the child to implement as freely as required.

    Regarding method hiding so that is only possible with static methods. Overriding in java does not hide the method since its at instance level. However for static methods, since the method is at class level, polymorphism is not possible , and thus while they are inherited if a sub class creates a static method with the same name,arguments and return type and tries to access the method statically the sub classes version would be called and not the super classes version as the sub class has now effictively hidden the method from the super class.