Should inheritance (of non-interface types) be removed from programming languages?

前端 未结 20 2285
旧时难觅i
旧时难觅i 2020-12-30 05:20

This is quite a controversial topic, and before you say \"no\", is it really, really needed?

I have been programming for about 10 years, and I can\'t honestly sa

20条回答
  •  感情败类
    2020-12-30 05:51

    I guess I have to play the devil's advocate. If we didn't have inheritance then we wouldn't be able to inherit abstract classes that uses the template method pattern. There are lots of examples where this is used in frameworks such as .NET and Java. Thread in Java is such an example:

    // Alternative 1:
    public class MyThread extends Thread {
    
        // Abstract method to implement from Thread
        // aka. "template method" (GoF design pattern)
        public void run() {
            // ...
        }
    }
    
    // Usage:
    MyThread t = new MyThread();
    t.start();
    

    The alternative is, in my meaning, verbose when you have to use it. Visual clutteer complexity goes up. This is because you need to create the Thread before you can actually use it.

    // Alternative 2:
    public class MyThread implements Runnable {
        // Method to implement from Runnable:
        public void run() {
            // ...
        }
    }
    
    // Usage:
    MyThread m = new MyThread();
    Thread t = new Thread(m);
    t.start();
    // …or if you have a curious perversion towards one-liners
    Thread t = new Thread(new MyThread());
    t.start();
    

    Having my devil's advocate hat off I guess you could argue that the gain in the second implementation is dependency injection or seperation of concerns which helps designing testable classes. Depending on your definition of what an interface is (I've heard of at least three) an abstract class could be regarded as an interface.

提交回复
热议问题