java中如果我们有抽象类,为什么还要接口?

Why Interfaces in Java if we have abstract class?

本问题已经有最佳答案,请猛点这里访问。

我有两个问题

  • 我们为什么需要Java中的接口,即使抽象类可以做接口的功能吗?在搜索时,我发现了一个抽象类无法完成接口功能的地方,这就是类需要实现多个接口的时候。它是在Java中提出接口概念的唯一原因吗?

  • 静态最终变量在接口中的用途是什么?需要在接口中声明变量用法的示例程序是受欢迎的。

  • 事先谢谢。


  • 正如您所说,只能从一个抽象类继承,但可以从多个接口继承。此外,继承意味着"is-a"关系,但接口指定了对象必须支持的一些操作集——本质上是它的行为。我认为这些是单独的想法。根据我的经验,类往往是名词(如IntegerList),接口是动词(如CloneableSerializable)。

  • 如果一个类实现了一个带有常量的接口,那么该类可以引用那些没有限定类名(javapractices.com)的常量。然而,正如这篇文章所解释的,这是一个糟糕的做法。


  • 接口在这些上下文中很有用:

    1—>正如你提到的,在Java中,我们只能扩展一个类,但可以实现多个接口。这实际上是实现的。例如,如果要在类中创建后台线程,并且扩展某个类以重用性,那么扩展线程类有多坏?在这种情况下,runnable来拯救,这是一个接口。

    2->也可以通过接口帮助我们实现某种设计模式。

    3->也可作为可标记的接口,例如可序列化接口。

    接口中的变量是充当gloabal的静态变量,可以与实现该接口的所有类共享。


    Why do we need interface in java even if abstract class can do the
    functionality of interfaces? On searching i found a place where
    abstract class fails to do the functionality of interfaces, that is
    when a class needs to implement multiple interfaces. Is it the only
    reason for bringing up the interfaces concept in java?

    Java不支持多类继承。所以你可以实现多个接口。更重要的是,您可以同时实现接口和扩展其他类。如果使用抽象类代替接口,这是不可能的。

    What is the use of variables in interfaces? Need example programs that
    state usage of variables in interfaces are welcome.

    您在接口中声明的任何"字段"都将是公共静态最终字段。换句话说,一个常数。因此,如果您想在所有子类中使用任何常量,那么您可以在接口中定义这些常量。


    1。

    Is it the only reason for bringing up the interfaces concept in java?

    对。另请参见接口与抽象类(常规OO):

    interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).

    2。

    What is the use of variables in interfaces? Need example programs that state usage of variables in interfaces are welcome.

    你是说静态变量?我不会在接口中使用"有状态的"静态变量,但是静态常量是可以的——这样您就可以添加与接口定义方式相关的额外信息。


    1)放入一个简单的句子:类可以实现几乎无限多个接口,但只能扩展一个(抽象)类。抽象类可能包含代码——通常是子类之间共享的基本实现。

    看看ArrayList类:

    1
    2
    3
    public class ArrayList<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, Serializable

    没有接口这是不可能的…

    第二)接口中没有变量。默认情况下,它们是public final

    第三)使用接口,您可以创建以接口为元素类型的集合,并用完全不同类型的对象填充它,这些对象没有公共的基类(不包括Object)。

    如果没有接口,您只能拥有Object的集合,并检查每个对象的类型和强制转换。

    通过接口,您可以将它们视为该接口的实现,并在不知道具体类型的情况下对它们调用接口的方法。