Is OOP & completely avoiding implementation inheritance possible?

前端 未结 8 2294
故里飘歌
故里飘歌 2020-12-15 05:34

I will choose Java as an example, most people know it, though every other OO language was working as well.

Java, like many other languages, has interface inheritance

相关标签:
8条回答
  • 2020-12-15 05:59

    The problem with most example against inheritance are examples where the person is using inheritance incorrectly, not a failure of inheritance to correctly abstract.

    In the article you posted a link to, the author shows the "brokenness" of inheritance using Stack and ArrayList. The example is flawed because a Stack is not an ArrayList and therefore inheritance should not be used. The example is as flawed as String extending Character, or PointXY extending Number.

    Before you extend class, you should always perform the "is_a" test. Since you can't say Every Stack is an ArrayList without being wrong in some way, then you should not inheirit.

    The contract for Stack is different than the contract for ArrayList (or List) and stack should not be inheriting methods that is does not care about (like get(int i) and add()). In fact Stack should be an interface with methods such as:

    interface Stack<T> {
       public void push(T object);
       public T pop();
       public void clear();
       public int size();
    }
    

    A class like ArrayListStack might implement the Stack interface, and in that case use composition (having an internal ArrayList) and not inheritance.

    Inheritance is not bad, bad inheritance is bad.

    0 讨论(0)
  • 2020-12-15 05:59

    You could also use composition and the strategy pattern.link text

    public class Car
    {
      private ICar _car;
    
      public void Move() {
         _car.Move();
      }
    }
    

    This is far more flexible than using inheritance based behaviour as it allows you to change at runtime, by substituting new Car types as required.

    0 讨论(0)
提交回复
热议问题