我何时必须使用接口而不是抽象类? [重复]

时间:2022-09-25 12:24:31

This question already has an answer here:

这个问题在这里已有答案:

I was wondering when I should use interfaces.

我想知道什么时候应该使用接口。

Lets think about the following:

让我们考虑以下事项:

public abstract class Vehicle {
   abstract float getSpeed();
}

and :

并且:

public interface IVehicle {
  float getSpeed();
}

I can easily implement both of them, they have the same functionality... BUT I also can add some variables to my vehicle class, which probably should be used in an vehicle (maxSpeed, carType...)

我可以很容易地实现它们,它们具有相同的功能......但是我也可以在车辆类中添加一些变量,这些变量可能应该用在车辆中(maxSpeed,carType ......)

What is the reason to use interfaces?

使用接口的原因是什么?

Thanks!

谢谢!

EDIT: I found a nice link about it in another thread: http://www.thecoldsun.com/en/content/01-2009/abstract-classes-and-interfaces

编辑:我在另一个帖子中找到了一个很好的链接:http://www.thecoldsun.com/en/content/01-2009/abstract-classes-and-interfaces

21 个解决方案

#1


89  

From Java How to Program about abstract classes:

从Java如何编程关于抽象类:

Because they’re used only as superclasses in inheritance hierarchies, we refer to them as abstract superclasses. These classes cannot be used to instantiate objects, because abstract classes are incomplete. Subclasses must declare the “missing pieces” to become “concrete” classes, from which you can instantiate objects. Otherwise, these subclasses, too, will be abstract.

因为它们仅用作继承层次结构中的超类,所以我们将它们称为抽象超类。这些类不能用于实例化对象,因为抽象类是不完整的。子类必须声明“缺失的部分”成为“具体”类,您可以从中实例化对象。否则,这些子类也将是抽象的。

To answer your question "What is the reason to use interfaces?":

回答你的问题“使用接口的原因是什么?”:

An abstract class’s purpose is to provide an appropriate superclass from which other classes can inherit and thus share a common design.

抽象类的目的是提供一个适当的超类,其他类可以从中继承并共享一个共同的设计。

As opposed to an interface:

与界面相反:

An interface describes a set of methods that can be called on an object, but does not provide concrete implementations for all the methods... Once a class implements an interface, all objects of that class have an is-a relationship with the interface type, and all objects of the class are guaranteed to provide the functionality described by the interface. This is true of all subclasses of that class as well.

接口描述了一组可以在对象上调用的方法,但没有为所有方法提供具体的实现......一旦类实现了接口,该类的所有对象都与接口类型具有is-a关系,并保证类的所有对象都提供接口描述的功能。对于该类的所有子类也是如此。

So, to answer your question "I was wondering when I should use interfaces", I think you should use interfaces when you want a full implementation and use abstract classes when you want partial pieces for your design (for reusability)

因此,回答你的问题“我想知道何时应该使用接口”,我认为你应该在需要完整实现时使用接口,并在需要部分设计时使用抽象类(为了可重用性)

#2


15  

Which should you use, abstract classes or interfaces?

你应该使用哪些,抽象类或接口?

Consider using abstract classes if any of these statements apply to your situation:

如果任何这些语句适用于您的情况,请考虑使用抽象类:

You want to share code among several closely related classes.

您希望在几个密切相关的类之间共享代码。

You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).

您希望扩展抽象类的类具有许多常用方法或字段,或者需要除公共之外的访问修饰符(例如protected和private)。

You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

您想声明非静态或非最终字段。这使您可以定义可以访问和修改它们所属对象的状态的方法。

Consider using interfaces if any of these statements apply to your situation:

如果任何这些语句适用于您的情况,请考虑使用接口:

You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.

您希望不相关的类将实现您的接口。例如,Comparable和Cloneable接口由许多不相关的类实现。

You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.

您希望指定特定数据类型的行为,但不关心谁实现其行为。

You want to take advantage of multiple inheritance of type.

您希望利用类型的多重继承。

#3


14  

From the Oracle tutorials :

来自Oracle教程:

Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

与接口不同,抽象类可以包含非静态和最终的字段,并且它们可以包含已实现的方法。这些抽象类与接口类似,不同之处在于它们提供部分实现,将其留给子类来完成实现。如果抽象类只包含抽象方法声明,则应将其声明为接口。

Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.

多个接口可以由类层次结构中的任何位置的类实现,无论它们是否以任何方式彼此相关。例如,可以考虑可比较或可克隆。

By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).

相比之下,抽象类最常被子类化以共享实现部分。单个抽象类由具有许多共同点(抽象类的已实现部分)的类似类子类化,但也有一些差异(抽象方法)。

#4


8  

Many cases can be implemented in both class types.

许多情况都可以在两种类中实现。

Interfaces are usefull when you want to define a class that has to have at least basic functions. Like a real interface for example USB.

当您想要定义必须至少具有基本功能的类时,接口很有用。像真正的接口,例如USB。

interface USB {
    public function sendPower(); //charge iphone for example
    public function sendData(); //itunes
    public function recieveData();
}

Use abstract classes when there are several ways to to implement an object.

当有多种方法来实现对象时,请使用抽象类。

abstract class MobilePhone {
    public function isIphone();

    public function charge() {
        //get some power, all phones need that
    }
}

class iPhone extends MobilePhone {
    public function isIphone() { return true; }
}

#5


7  

There are a number of times you might consider using an interface over an abstract implementation

您可能会多次考虑在抽象实现上使用接口

  • When the available abstract implementation doesn't do what you want and you want to create your own
  • 当可用的抽象实现没有做你想要的,你想创建自己的
  • when you have an existing class (that extends from other class) and you want to implement the functionality of the interface
  • 当你有一个现有的类(从其他类扩展)并且你想要实现接口的功能

Generally speaking, interfaces were introduced to overcome the lack of multiple inheritancy, amongst other things

一般而言,引入接口是为了克服缺乏多重继承性等问题

#6


3  

With support of default methods in interface since launch of Java 8, the gap between interface and abstract classes has been reduced but still they have major differences.

自Java 8发布以来,在接口中支持默认方法,接口和抽象类之间的差距已经缩小,但仍然存在重大差异。

  1. Variables in interface are public static final. But abstract class can have other type of variables like private, protected etc

    接口中的变量是public static final。但是抽象类可以有其他类型的变量,如private,protected等

  2. Methods in interface are public or public static but methods in abstract class can be private and protected too

    接口中的方法是public或public static,但抽象类中的方法也可以是私有的,也可以是受保护的

  3. Use abstract class to establish relation between interrelated objects. Use interface to establish relation between unrelated classes.

    使用抽象类来建立相互关联的对象之间的关系。使用接口建立不相关类之间的关系。

Have a look at this article for special properties of interface in java 8. static modifier for default methods in interface causes compile time error in derived error if you want to use @override.

看一下这篇文章,了解java 8中接口的特殊属性。如果你想使用@override,接口默认方法的静态修饰符会导致派生错误中的编译时错误。

This article explains why default methods have been introduced in java 8 : To enhance the Collections API in Java 8 to support lambda expressions.

本文解释了为什么在Java 8中引入了默认方法:在Java 8中增强Collections API以支持lambda表达式。

Have a look at oracle documentation too to understand the differences in better way.

看看oracle文档也可以更好地理解差异。

Have a look at this related SE questions with code example to understand things in better way:

通过代码示例查看这些相关的SE问题,以更好的方式理解事物:

How should I have explained the difference between an Interface and an Abstract class?

我该如何解释Interface和Abstract类之间的区别?

#7


2  

Referring blog: https://mybolder.com/2015/12/02/when-to-use-abstract-class-and-intreface/

参考博客:https://mybolder.com/2015/12/02/when-to-use-abstract-class-and-intreface/

Which should you use, abstract classes or interfaces?

你应该使用哪些,抽象类或接口?

Consider using abstract classes if any of these statements apply to your situation:

如果任何这些语句适用于您的情况,请考虑使用抽象类:

  1. You want to share code among several closely related classes.
  2. 您希望在几个密切相关的类之间共享代码。
  3. You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  4. 您希望扩展抽象类的类具有许多常用方法或字段,或者需要除公共之外的访问修饰符(例如protected和private)。
  5. You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
  6. 您想声明非静态或非最终字段。这使您可以定义可以访问和修改它们所属对象的状态的方法。

Consider using interfaces if any of these statements apply to your situation:

如果任何这些语句适用于您的情况,请考虑使用接口:

  1. You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
  2. 您希望不相关的类将实现您的接口。例如,Comparable和Cloneable接口由许多不相关的类实现。
  3. You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
  4. 您希望指定特定数据类型的行为,但不关心谁实现其行为。
  5. You want to take advantage of multiple inheritance of type.
  6. 您希望利用类型的多重继承。

An example of an abstract class in the JDK is AbstractMap, which is part of the Collections Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap) share many methods (including get, put, isEmpty, containsKey, and containsValue) that AbstractMap defines.

JDK中的抽象类的一个示例是AbstractMap,它是Collections Framework的一部分。它的子类(包括HashMap,TreeMap和ConcurrentHashMap)共享AbstractMap定义的许多方法(包括get,put,isEmpty,containsKey和containsValue)。

#8


1  

Considering Java:

考虑Java:

Interfaces:

接口:

  • Are a fundamental OOP abstraction.
  • 是一个基本的OOP抽象。
  • Will often (but not always) yield clearer code than abstract classes.
  • 通常(但不总是)会产生比抽象类更清晰的代码。
  • Can be implemented by multiple concrete classes to suit different situations.
  • 可以通过多个具体类来实现,以适应不同的情况。
  • Can directly implement scenarios calling for multiple inheritance.
  • 可以直接实现调用多重继承的场景。
  • Can be more easily mocked out for testing purposes.
  • 可以更容易地模拟出来进行测试。
  • Are useful for JDK proxies (see java.lang.reflect.Proxy).
  • 对JDK代理有用(请参阅java.lang.reflect.Proxy)。

These are just the beginning of a very long list of pros/cons for interfaces vs. abstract classes.

这些只是接口与抽象类的很长的优缺点列表的开头。

#9


1  

This is an direct excerpt from the excellent book 'Thinking in Java' by Bruce Eckel.

这是Bruce Eckel出版的优秀着作“Thinking in Java”的直接摘录。

[..] Should you use an interface or an abstract class?

[..]你应该使用接口还是抽象类?

Well, an interface gives you the benefits of an abstract class and the benefits of an interface, so if it’s possible to create your base class without any method definitions or member variables you should always prefer interfaces to abstract classes.

好吧,一个接口为您提供了抽象类的好处和接口的好处,因此如果可以创建没有任何方法定义或成员变量的基类,您应该总是更喜欢接口到抽象类。

In fact, if you know something is going to be a base class, your first choice should be to make it an interface, and only if you’re forced to have method definitions or member variables should you change to an abstract class.

实际上,如果您知道某些东西将成为基类,那么您的第一选择应该是使其成为一个接口,并且只有当您*拥有方法定义或成员变量时才应该更改为抽象类。

#10


1  

Use an abstract class when you want to define a template for a group of sub-classes , and you have at least some implementation code that call sub-classes could use.

如果要为一组子类定义模板,请使用抽象类,并且至少有一些调用子类可以使用的实现代码。

Use an interface when you want to define the role that other classes can play, regardless of where those classes are in the inheritance tree

如果要定义其他类可以播放的角色,请使用接口,而不管这些类在继承树中的位置

you extend an abstract class

你扩展了一个抽象类

you implement an interface :)

你实现了一个接口:)

in an interface all the fields are automatically public static final and all the methods are public whereas an abstract class allows you a bit of flexibility here.

在一个接口中,所有字段都是自动公共静态final,所有方法都是公共的,而抽象类允许你在这里有一点灵活性。

#11


0  

Abstract classes can contain methods that are not abstract, whereas in interfaces all your methods are abstract and have to be implemented.

抽象类可以包含非抽象的方法,而在接口中,所有方法都是抽象的,必须实现。

You should use interfaces instead when you know you will always implement those certain methods. Also you can inherit from multiple interfaces, it is java's way of dealing with multiple inheritance

当您知道将始终实现这些特定方法时,您应该使用接口。你也可以从多个接口继承,这是java处理多重继承的方式

#12


0  

interface is basically used when two parties works together,and one party want to hide something from other(or only want to show some part of his class).than we use interface eg. in jdbc jdbc vendors provide us some interfaces bcoz they want to hide everything from us.

界面基本上是在两方合作时使用的,一方想要隐藏其他东西(或者只是想展示他班级的某些部分)。然后我们使用界面例如。在jdbc jdbc供应商为我们提供了一些bcoz接口,他们希望隐藏我们的一切。

abstract class is only used in that case when we want to support a common behavior in more than one classes...or want to provide some preimplemented implementation with some unimplemented methods(methods should be abstract). eg. http servlet in servlet interface is an abstract class bcoz this class implements servlet interface except it's service method...so this class help us to get some preimplemetation of interface method...

抽象类仅在我们想要支持多个类中的公共行为时使用...或者想要使用一些未实现的方法提供一些预实现的实现(方法应该是抽象的)。例如。 servlet接口中的http servlet是一个抽象类bcoz这个类实现了servlet接口,除了它的服务方法...所以这个类帮助我们得到一些接口方法的预先实现...

#13


0  

Actually Interface and abstract class are used to just specify some contract/rules which will just show, how their sub classes will be.

实际上,接口和抽象类只用于指定一些合同/规则,它们只显示它们的子类将如何。

Mostly we know that interface is a pure abstract.Means there you cant specify a single method with body.This particular point is the advantages of abstract class.Means in abstract class u have right to specify method with body and without body as-well.

大多数情况下,我们知道接口是一个纯粹的抽象。在那里你不能用body指定一个方法。这个特殊点是抽象类的优点。抽象类中的元素你有权用body指定方法,没有正文。

So if u want to specify something about ur subclass, then u may go for interface. But if u also want to specify something for ur sub classes and u want also ur class should also have some own method.Then in that case u may go for abstract class

所以,如果你想指定关于你的子类的东西,那么你可以去接口。但是,如果你也想为你的子类指定一些东西,你也希望你的类也应该有一些自己的方法。那么在那种情况下你可以去抽象类

#14


0  

You cant achieve multiple inheritance with abstract class that is why sun microsystem provide interfaces.

您无法使用抽象类实现多重继承,这就是sun微系统提供接口的原因。

You cannot extend two classes but you can implement multiple interfaces

您不能扩展两个类,但可以实现多个接口

#15


0  

Interface and Abstract Class are the two different ways to achieve Abstraction in OOP Languages.

接口和抽象类是在OOP语言中实现抽象的两种不同方式。

Interface provides 100% abstraction, i.e all methods are abstract.

接口提供100%抽象,即所有方法都是抽象的。

Abstract class provides 0 to 100% abstraction, i.e it may have or may not have abstract methods.

抽象类提供0到100%的抽象,即它可能有或没有抽象方法。

We can use Interface when we want all the functionality of a type to be implemented by the client.

当我们希望客户端实现类型的所有功能时,我们可以使用Interface。

We can use Abstract Class when some common functionality can be provided by Abstract Class implementer and client will be given chance to implement what he needs actually.

当抽象类实现者可以提供一些常用功能时,我们可以使用抽象类,客户端将有机会实现他实际需要的东西。

#16


0  

Abstract Class : Use it when there is strong is-a relation between super class and sub class and all subclass share some common behavior .

抽象类:当超类和子类之间存在强大的关系时使用它,并且所有子类都有一些共同的行为。

Interface : It define just protocol which all subclass need to follow.

接口:它定义了所有子类需要遵循的协议。

#17


0  

The answer of this question is very simple,Whatever we can do with interface can be done with abstract class Agree...so when to use interfaces,the answer lies in C# restriction of multiple inheritance. When you have only contracts(abstracts) to declare and want your sub-classes implement it go with interfaces, because if you use abstract class in this case, you can not inherit from one more class and you are stuck if want to inherit from one more class,but you can implement as many interfaces.

这个问题的答案很简单,无论我们用接口做什么都可以用抽象类同步来完成...所以当使用接口时,答案就在于C#多重继承的限制。当你只有声明的合同(摘要)并希望你的子类实现它时,请使用接口,因为如果你在这种情况下使用抽象类,你就不能继承另一个类,如果你想从一个类继承你就会陷入困境更多类,但您可以实现尽可能多的接口。

#18


0  

If you are using JDK 8, there is no reason to use abstract classes because whatever we do with abstract classes we can now do it with interfaces because of default methods. If you use abstract class you have to extend it and there is a restriction that you can extends only once. But if you use interface you can implements as many as you want.

如果您使用的是JDK 8,则没有理由使用抽象类,因为无论我们使用抽象类,我们现在可以使用默认方法来使用接口。如果你使用抽象类,你必须扩展它,并且有一个限制,你只能扩展一次。但是如果你使用界面,你可以实现任意多个。

Interface is by default an abstract class an all methods and constructors are public.

接口默认为抽象类,所有方法和构造函数都是公共的。

#19


0  

I found this very good explanation here hope it helps someone. read it here

我发现这个非常好的解释,希望它可以帮助某人。在这里阅读

#20


-1  

Interfaces and abstracted classes seem very similar, however, there are important differences between them.

接口和抽象类似乎非常相似,但它们之间存在重要差异。

Abstraction is based on a good "is-a" relationship. Meaning that you would say that a car is a Honda, and a Honda is a car. Using abstraction on a class means you can also have abstract methods. This would require any subclass extended from it to obtain the abstract methods and override them. Using the example below, we can create an abstract howToStart(); method that will require each class to implement it.

抽象是基于良好的“is-a”关系。这意味着你会说汽车是本田汽车,而本田汽车则是汽车。在类上使用抽象意味着您也可以使用抽象方法。这将需要从中扩展的任何子类来获取抽象方法并覆盖它们。使用下面的例子,我们可以创建一个抽象的howToStart();需要每个类实现它的方法。

Through abstraction, we can provide similarities between code so we would still have a base class. Using an example of the Car class idea we could create:

通过抽象,我们可以提供代码之间的相似性,因此我们仍然可以使用基类。使用Car类理念的一个例子,我们可以创建:

public abstract class Car{
    private String make;
    private String model

    protected Car() { }  // Default constructor

    protect Car(String make, String model){
        //Assign values to 
    }

    public abstract void howToStart();
}

Then with the Honda class we would have:

然后在本田课上我们会:

public class Honda extends implements Engine {

    public Honda() { }  // Default constructor

    public Honda(String make, String model){
        //Assign values
    }

    @Override
    public static void howToStart(){
        // Code on how to start
    }

}

Interfaces are based on the "has-a" relationship. This would mean you could say a car has-a engine, but an engine is not a car. In the above example, Honda has implements Engine.

接口基于“has-a”关系。这意味着你可以说汽车有发动机,但发动机不是汽车。在上面的例子中,Honda实现了Engine。

For the engine interface we could create:

对于引擎接口,我们可以创建:

public interface Engine {
    public void startup();
}

The interface will provide a many-to-one instance. So we could apply the Engine interface to any type of car. We can also extend it to other object. Like if we were to make a boat class, and have sub classes of boat types, we could extend Engine and have the sub classes of boat require the startup(); method. Interfaces are good for creating framework to various classes that have some similarities. We can also implement multiple instances in one class, such as:

该接口将提供多对一实例。因此我们可以将引擎接口应用于任何类型的汽车。我们也可以将它扩展到其他对象。就像我们要制作一个船类,并且有船类的子类一样,我们可以扩展Engine并且让子类的船需要启动();方法。接口适用于为具有某些相似性的各种类创建框架。我们还可以在一个类中实现多个实例,例如:

public class Honda extends implements Engine, Transmission, List<Parts>

Hopefully this helps.

希望这会有所帮助。

#21


-2  

If you are in a situation where your Interface method implementation is same for all the inherting classes then you do not need interface, instead Abstract class should had been used. When you want something to be followed by every class (must have) and there implementation would differ or not defined then we go for Interface.

如果您所有的inherting类的Interface方法实现相同,那么您不需要接口,而应该使用Abstract类。如果你想要每个类(必须有)后面的东西,并且实现会有所不同或没有定义,那么我们去接口。

#1


89  

From Java How to Program about abstract classes:

从Java如何编程关于抽象类:

Because they’re used only as superclasses in inheritance hierarchies, we refer to them as abstract superclasses. These classes cannot be used to instantiate objects, because abstract classes are incomplete. Subclasses must declare the “missing pieces” to become “concrete” classes, from which you can instantiate objects. Otherwise, these subclasses, too, will be abstract.

因为它们仅用作继承层次结构中的超类,所以我们将它们称为抽象超类。这些类不能用于实例化对象,因为抽象类是不完整的。子类必须声明“缺失的部分”成为“具体”类,您可以从中实例化对象。否则,这些子类也将是抽象的。

To answer your question "What is the reason to use interfaces?":

回答你的问题“使用接口的原因是什么?”:

An abstract class’s purpose is to provide an appropriate superclass from which other classes can inherit and thus share a common design.

抽象类的目的是提供一个适当的超类,其他类可以从中继承并共享一个共同的设计。

As opposed to an interface:

与界面相反:

An interface describes a set of methods that can be called on an object, but does not provide concrete implementations for all the methods... Once a class implements an interface, all objects of that class have an is-a relationship with the interface type, and all objects of the class are guaranteed to provide the functionality described by the interface. This is true of all subclasses of that class as well.

接口描述了一组可以在对象上调用的方法,但没有为所有方法提供具体的实现......一旦类实现了接口,该类的所有对象都与接口类型具有is-a关系,并保证类的所有对象都提供接口描述的功能。对于该类的所有子类也是如此。

So, to answer your question "I was wondering when I should use interfaces", I think you should use interfaces when you want a full implementation and use abstract classes when you want partial pieces for your design (for reusability)

因此,回答你的问题“我想知道何时应该使用接口”,我认为你应该在需要完整实现时使用接口,并在需要部分设计时使用抽象类(为了可重用性)

#2


15  

Which should you use, abstract classes or interfaces?

你应该使用哪些,抽象类或接口?

Consider using abstract classes if any of these statements apply to your situation:

如果任何这些语句适用于您的情况,请考虑使用抽象类:

You want to share code among several closely related classes.

您希望在几个密切相关的类之间共享代码。

You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).

您希望扩展抽象类的类具有许多常用方法或字段,或者需要除公共之外的访问修饰符(例如protected和private)。

You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

您想声明非静态或非最终字段。这使您可以定义可以访问和修改它们所属对象的状态的方法。

Consider using interfaces if any of these statements apply to your situation:

如果任何这些语句适用于您的情况,请考虑使用接口:

You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.

您希望不相关的类将实现您的接口。例如,Comparable和Cloneable接口由许多不相关的类实现。

You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.

您希望指定特定数据类型的行为,但不关心谁实现其行为。

You want to take advantage of multiple inheritance of type.

您希望利用类型的多重继承。

#3


14  

From the Oracle tutorials :

来自Oracle教程:

Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

与接口不同,抽象类可以包含非静态和最终的字段,并且它们可以包含已实现的方法。这些抽象类与接口类似,不同之处在于它们提供部分实现,将其留给子类来完成实现。如果抽象类只包含抽象方法声明,则应将其声明为接口。

Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.

多个接口可以由类层次结构中的任何位置的类实现,无论它们是否以任何方式彼此相关。例如,可以考虑可比较或可克隆。

By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).

相比之下,抽象类最常被子类化以共享实现部分。单个抽象类由具有许多共同点(抽象类的已实现部分)的类似类子类化,但也有一些差异(抽象方法)。

#4


8  

Many cases can be implemented in both class types.

许多情况都可以在两种类中实现。

Interfaces are usefull when you want to define a class that has to have at least basic functions. Like a real interface for example USB.

当您想要定义必须至少具有基本功能的类时,接口很有用。像真正的接口,例如USB。

interface USB {
    public function sendPower(); //charge iphone for example
    public function sendData(); //itunes
    public function recieveData();
}

Use abstract classes when there are several ways to to implement an object.

当有多种方法来实现对象时,请使用抽象类。

abstract class MobilePhone {
    public function isIphone();

    public function charge() {
        //get some power, all phones need that
    }
}

class iPhone extends MobilePhone {
    public function isIphone() { return true; }
}

#5


7  

There are a number of times you might consider using an interface over an abstract implementation

您可能会多次考虑在抽象实现上使用接口

  • When the available abstract implementation doesn't do what you want and you want to create your own
  • 当可用的抽象实现没有做你想要的,你想创建自己的
  • when you have an existing class (that extends from other class) and you want to implement the functionality of the interface
  • 当你有一个现有的类(从其他类扩展)并且你想要实现接口的功能

Generally speaking, interfaces were introduced to overcome the lack of multiple inheritancy, amongst other things

一般而言,引入接口是为了克服缺乏多重继承性等问题

#6


3  

With support of default methods in interface since launch of Java 8, the gap between interface and abstract classes has been reduced but still they have major differences.

自Java 8发布以来,在接口中支持默认方法,接口和抽象类之间的差距已经缩小,但仍然存在重大差异。

  1. Variables in interface are public static final. But abstract class can have other type of variables like private, protected etc

    接口中的变量是public static final。但是抽象类可以有其他类型的变量,如private,protected等

  2. Methods in interface are public or public static but methods in abstract class can be private and protected too

    接口中的方法是public或public static,但抽象类中的方法也可以是私有的,也可以是受保护的

  3. Use abstract class to establish relation between interrelated objects. Use interface to establish relation between unrelated classes.

    使用抽象类来建立相互关联的对象之间的关系。使用接口建立不相关类之间的关系。

Have a look at this article for special properties of interface in java 8. static modifier for default methods in interface causes compile time error in derived error if you want to use @override.

看一下这篇文章,了解java 8中接口的特殊属性。如果你想使用@override,接口默认方法的静态修饰符会导致派生错误中的编译时错误。

This article explains why default methods have been introduced in java 8 : To enhance the Collections API in Java 8 to support lambda expressions.

本文解释了为什么在Java 8中引入了默认方法:在Java 8中增强Collections API以支持lambda表达式。

Have a look at oracle documentation too to understand the differences in better way.

看看oracle文档也可以更好地理解差异。

Have a look at this related SE questions with code example to understand things in better way:

通过代码示例查看这些相关的SE问题,以更好的方式理解事物:

How should I have explained the difference between an Interface and an Abstract class?

我该如何解释Interface和Abstract类之间的区别?

#7


2  

Referring blog: https://mybolder.com/2015/12/02/when-to-use-abstract-class-and-intreface/

参考博客:https://mybolder.com/2015/12/02/when-to-use-abstract-class-and-intreface/

Which should you use, abstract classes or interfaces?

你应该使用哪些,抽象类或接口?

Consider using abstract classes if any of these statements apply to your situation:

如果任何这些语句适用于您的情况,请考虑使用抽象类:

  1. You want to share code among several closely related classes.
  2. 您希望在几个密切相关的类之间共享代码。
  3. You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  4. 您希望扩展抽象类的类具有许多常用方法或字段,或者需要除公共之外的访问修饰符(例如protected和private)。
  5. You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
  6. 您想声明非静态或非最终字段。这使您可以定义可以访问和修改它们所属对象的状态的方法。

Consider using interfaces if any of these statements apply to your situation:

如果任何这些语句适用于您的情况,请考虑使用接口:

  1. You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
  2. 您希望不相关的类将实现您的接口。例如,Comparable和Cloneable接口由许多不相关的类实现。
  3. You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
  4. 您希望指定特定数据类型的行为,但不关心谁实现其行为。
  5. You want to take advantage of multiple inheritance of type.
  6. 您希望利用类型的多重继承。

An example of an abstract class in the JDK is AbstractMap, which is part of the Collections Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap) share many methods (including get, put, isEmpty, containsKey, and containsValue) that AbstractMap defines.

JDK中的抽象类的一个示例是AbstractMap,它是Collections Framework的一部分。它的子类(包括HashMap,TreeMap和ConcurrentHashMap)共享AbstractMap定义的许多方法(包括get,put,isEmpty,containsKey和containsValue)。

#8


1  

Considering Java:

考虑Java:

Interfaces:

接口:

  • Are a fundamental OOP abstraction.
  • 是一个基本的OOP抽象。
  • Will often (but not always) yield clearer code than abstract classes.
  • 通常(但不总是)会产生比抽象类更清晰的代码。
  • Can be implemented by multiple concrete classes to suit different situations.
  • 可以通过多个具体类来实现,以适应不同的情况。
  • Can directly implement scenarios calling for multiple inheritance.
  • 可以直接实现调用多重继承的场景。
  • Can be more easily mocked out for testing purposes.
  • 可以更容易地模拟出来进行测试。
  • Are useful for JDK proxies (see java.lang.reflect.Proxy).
  • 对JDK代理有用(请参阅java.lang.reflect.Proxy)。

These are just the beginning of a very long list of pros/cons for interfaces vs. abstract classes.

这些只是接口与抽象类的很长的优缺点列表的开头。

#9


1  

This is an direct excerpt from the excellent book 'Thinking in Java' by Bruce Eckel.

这是Bruce Eckel出版的优秀着作“Thinking in Java”的直接摘录。

[..] Should you use an interface or an abstract class?

[..]你应该使用接口还是抽象类?

Well, an interface gives you the benefits of an abstract class and the benefits of an interface, so if it’s possible to create your base class without any method definitions or member variables you should always prefer interfaces to abstract classes.

好吧,一个接口为您提供了抽象类的好处和接口的好处,因此如果可以创建没有任何方法定义或成员变量的基类,您应该总是更喜欢接口到抽象类。

In fact, if you know something is going to be a base class, your first choice should be to make it an interface, and only if you’re forced to have method definitions or member variables should you change to an abstract class.

实际上,如果您知道某些东西将成为基类,那么您的第一选择应该是使其成为一个接口,并且只有当您*拥有方法定义或成员变量时才应该更改为抽象类。

#10


1  

Use an abstract class when you want to define a template for a group of sub-classes , and you have at least some implementation code that call sub-classes could use.

如果要为一组子类定义模板,请使用抽象类,并且至少有一些调用子类可以使用的实现代码。

Use an interface when you want to define the role that other classes can play, regardless of where those classes are in the inheritance tree

如果要定义其他类可以播放的角色,请使用接口,而不管这些类在继承树中的位置

you extend an abstract class

你扩展了一个抽象类

you implement an interface :)

你实现了一个接口:)

in an interface all the fields are automatically public static final and all the methods are public whereas an abstract class allows you a bit of flexibility here.

在一个接口中,所有字段都是自动公共静态final,所有方法都是公共的,而抽象类允许你在这里有一点灵活性。

#11


0  

Abstract classes can contain methods that are not abstract, whereas in interfaces all your methods are abstract and have to be implemented.

抽象类可以包含非抽象的方法,而在接口中,所有方法都是抽象的,必须实现。

You should use interfaces instead when you know you will always implement those certain methods. Also you can inherit from multiple interfaces, it is java's way of dealing with multiple inheritance

当您知道将始终实现这些特定方法时,您应该使用接口。你也可以从多个接口继承,这是java处理多重继承的方式

#12


0  

interface is basically used when two parties works together,and one party want to hide something from other(or only want to show some part of his class).than we use interface eg. in jdbc jdbc vendors provide us some interfaces bcoz they want to hide everything from us.

界面基本上是在两方合作时使用的,一方想要隐藏其他东西(或者只是想展示他班级的某些部分)。然后我们使用界面例如。在jdbc jdbc供应商为我们提供了一些bcoz接口,他们希望隐藏我们的一切。

abstract class is only used in that case when we want to support a common behavior in more than one classes...or want to provide some preimplemented implementation with some unimplemented methods(methods should be abstract). eg. http servlet in servlet interface is an abstract class bcoz this class implements servlet interface except it's service method...so this class help us to get some preimplemetation of interface method...

抽象类仅在我们想要支持多个类中的公共行为时使用...或者想要使用一些未实现的方法提供一些预实现的实现(方法应该是抽象的)。例如。 servlet接口中的http servlet是一个抽象类bcoz这个类实现了servlet接口,除了它的服务方法...所以这个类帮助我们得到一些接口方法的预先实现...

#13


0  

Actually Interface and abstract class are used to just specify some contract/rules which will just show, how their sub classes will be.

实际上,接口和抽象类只用于指定一些合同/规则,它们只显示它们的子类将如何。

Mostly we know that interface is a pure abstract.Means there you cant specify a single method with body.This particular point is the advantages of abstract class.Means in abstract class u have right to specify method with body and without body as-well.

大多数情况下,我们知道接口是一个纯粹的抽象。在那里你不能用body指定一个方法。这个特殊点是抽象类的优点。抽象类中的元素你有权用body指定方法,没有正文。

So if u want to specify something about ur subclass, then u may go for interface. But if u also want to specify something for ur sub classes and u want also ur class should also have some own method.Then in that case u may go for abstract class

所以,如果你想指定关于你的子类的东西,那么你可以去接口。但是,如果你也想为你的子类指定一些东西,你也希望你的类也应该有一些自己的方法。那么在那种情况下你可以去抽象类

#14


0  

You cant achieve multiple inheritance with abstract class that is why sun microsystem provide interfaces.

您无法使用抽象类实现多重继承,这就是sun微系统提供接口的原因。

You cannot extend two classes but you can implement multiple interfaces

您不能扩展两个类,但可以实现多个接口

#15


0  

Interface and Abstract Class are the two different ways to achieve Abstraction in OOP Languages.

接口和抽象类是在OOP语言中实现抽象的两种不同方式。

Interface provides 100% abstraction, i.e all methods are abstract.

接口提供100%抽象,即所有方法都是抽象的。

Abstract class provides 0 to 100% abstraction, i.e it may have or may not have abstract methods.

抽象类提供0到100%的抽象,即它可能有或没有抽象方法。

We can use Interface when we want all the functionality of a type to be implemented by the client.

当我们希望客户端实现类型的所有功能时,我们可以使用Interface。

We can use Abstract Class when some common functionality can be provided by Abstract Class implementer and client will be given chance to implement what he needs actually.

当抽象类实现者可以提供一些常用功能时,我们可以使用抽象类,客户端将有机会实现他实际需要的东西。

#16


0  

Abstract Class : Use it when there is strong is-a relation between super class and sub class and all subclass share some common behavior .

抽象类:当超类和子类之间存在强大的关系时使用它,并且所有子类都有一些共同的行为。

Interface : It define just protocol which all subclass need to follow.

接口:它定义了所有子类需要遵循的协议。

#17


0  

The answer of this question is very simple,Whatever we can do with interface can be done with abstract class Agree...so when to use interfaces,the answer lies in C# restriction of multiple inheritance. When you have only contracts(abstracts) to declare and want your sub-classes implement it go with interfaces, because if you use abstract class in this case, you can not inherit from one more class and you are stuck if want to inherit from one more class,but you can implement as many interfaces.

这个问题的答案很简单,无论我们用接口做什么都可以用抽象类同步来完成...所以当使用接口时,答案就在于C#多重继承的限制。当你只有声明的合同(摘要)并希望你的子类实现它时,请使用接口,因为如果你在这种情况下使用抽象类,你就不能继承另一个类,如果你想从一个类继承你就会陷入困境更多类,但您可以实现尽可能多的接口。

#18


0  

If you are using JDK 8, there is no reason to use abstract classes because whatever we do with abstract classes we can now do it with interfaces because of default methods. If you use abstract class you have to extend it and there is a restriction that you can extends only once. But if you use interface you can implements as many as you want.

如果您使用的是JDK 8,则没有理由使用抽象类,因为无论我们使用抽象类,我们现在可以使用默认方法来使用接口。如果你使用抽象类,你必须扩展它,并且有一个限制,你只能扩展一次。但是如果你使用界面,你可以实现任意多个。

Interface is by default an abstract class an all methods and constructors are public.

接口默认为抽象类,所有方法和构造函数都是公共的。

#19


0  

I found this very good explanation here hope it helps someone. read it here

我发现这个非常好的解释,希望它可以帮助某人。在这里阅读

#20


-1  

Interfaces and abstracted classes seem very similar, however, there are important differences between them.

接口和抽象类似乎非常相似,但它们之间存在重要差异。

Abstraction is based on a good "is-a" relationship. Meaning that you would say that a car is a Honda, and a Honda is a car. Using abstraction on a class means you can also have abstract methods. This would require any subclass extended from it to obtain the abstract methods and override them. Using the example below, we can create an abstract howToStart(); method that will require each class to implement it.

抽象是基于良好的“is-a”关系。这意味着你会说汽车是本田汽车,而本田汽车则是汽车。在类上使用抽象意味着您也可以使用抽象方法。这将需要从中扩展的任何子类来获取抽象方法并覆盖它们。使用下面的例子,我们可以创建一个抽象的howToStart();需要每个类实现它的方法。

Through abstraction, we can provide similarities between code so we would still have a base class. Using an example of the Car class idea we could create:

通过抽象,我们可以提供代码之间的相似性,因此我们仍然可以使用基类。使用Car类理念的一个例子,我们可以创建:

public abstract class Car{
    private String make;
    private String model

    protected Car() { }  // Default constructor

    protect Car(String make, String model){
        //Assign values to 
    }

    public abstract void howToStart();
}

Then with the Honda class we would have:

然后在本田课上我们会:

public class Honda extends implements Engine {

    public Honda() { }  // Default constructor

    public Honda(String make, String model){
        //Assign values
    }

    @Override
    public static void howToStart(){
        // Code on how to start
    }

}

Interfaces are based on the "has-a" relationship. This would mean you could say a car has-a engine, but an engine is not a car. In the above example, Honda has implements Engine.

接口基于“has-a”关系。这意味着你可以说汽车有发动机,但发动机不是汽车。在上面的例子中,Honda实现了Engine。

For the engine interface we could create:

对于引擎接口,我们可以创建:

public interface Engine {
    public void startup();
}

The interface will provide a many-to-one instance. So we could apply the Engine interface to any type of car. We can also extend it to other object. Like if we were to make a boat class, and have sub classes of boat types, we could extend Engine and have the sub classes of boat require the startup(); method. Interfaces are good for creating framework to various classes that have some similarities. We can also implement multiple instances in one class, such as:

该接口将提供多对一实例。因此我们可以将引擎接口应用于任何类型的汽车。我们也可以将它扩展到其他对象。就像我们要制作一个船类,并且有船类的子类一样,我们可以扩展Engine并且让子类的船需要启动();方法。接口适用于为具有某些相似性的各种类创建框架。我们还可以在一个类中实现多个实例,例如:

public class Honda extends implements Engine, Transmission, List<Parts>

Hopefully this helps.

希望这会有所帮助。

#21


-2  

If you are in a situation where your Interface method implementation is same for all the inherting classes then you do not need interface, instead Abstract class should had been used. When you want something to be followed by every class (must have) and there implementation would differ or not defined then we go for Interface.

如果您所有的inherting类的Interface方法实现相同,那么您不需要接口,而应该使用Abstract类。如果你想要每个类(必须有)后面的东西,并且实现会有所不同或没有定义,那么我们去接口。