美文网首页
Interfaces and Abstract Classe(有

Interfaces and Abstract Classe(有

作者: 泰兰德的加长香蕉 | 来源:发表于2018-09-25 23:28 被阅读0次

    If you read the section about abstract classes in Chapter 5, you may wonder why the designers of the Java programming language bothered with introducing the concept of interfaces. Why can’t Comparable simply be an abstract class:

    abstract class Comparable // why not?

    {

        public abstract int compareTo(Object other);

    }

    The Employee class would then simply extend this abstract class and supply the compareTo method:

    class Employee extends Comparable // why not?

    {

        public int compareTo(Object other) { . . . }

    }

    There is, unfortunately, a major problem with using an abstract base class to express a generic property. A class can only extend a single class. Suppose that the Employee class already extends a different class, say, Person. Then it can’t extend a second class.

    class Employee extends Person, Comparable // ERROR

    But each class can implement as many interfaces as it likes:

    class Employee extends Person implements Comparable // OK

    Other programming languages, in particular C++, allow a class to have more than one superclass. This feature is called multiple inheritance. The designers of Java chose not to support multiple inheritance, because it makes the language either very complex (as in C++) or less efficient (as in Eiffel).

    Instead, interfaces afford most of the benefits of multiple inheritance while avoiding the complexities and inefficiencies.

    相关文章

      网友评论

          本文标题:Interfaces and Abstract Classe(有

          本文链接:https://www.haomeiwen.com/subject/xoproftx.html