界面和抽象类有什么区别?

界面和抽象类的区别究竟是什么?

接口

一个界面是一个合同 :编写界面的人说,“ 嘿,我接受这样的东西 ”,而使用这个界面的人说:“ 好吧,我写的那个类似这样看 ”。

一个接口是一个空壳 。 只有方法的签名,这意味着方法没有一个主体。 界面不能做任何事情。 这只是一个模式。

例如(伪代码):

// I say all motor vehicles should look like this: interface MotorVehicle { void run(); int getFuel(); } // My team mate complies and writes vehicle looking that way class Car implements MotorVehicle { int fuel; void run() { print("Wrroooooooom"); } int getFuel() { return this.fuel; } } 

实现一个接口只消耗很less的CPU,因为它不是一个类,只是一堆名字,因此没有任何昂贵的查找工作。 这很重要,比如embedded式设备。


抽象类

与接口不同,抽象类是类。 它们使用起来比较昂贵,因为从它们inheritance的时候有一个查找的办法。

抽象类看起来很像接口,但他们有更多的东西:你可以为它们定义一个行为。 更重要的是一个人说:“这些class应该是这样的,他们有这个共同点,所以填空!”

例如:

 // I say all motor vehicles should look like this: abstract class MotorVehicle { int fuel; // They ALL have fuel, so lets implement this for everybody. int getFuel() { return this.fuel; } // That can be very different, force them to provide their // own implementation. abstract void run(); } // My teammate complies and writes vehicle looking that way class Car extends MotorVehicle { void run() { print("Wrroooooooom"); } } 

履行

虽然抽象类和接口应该是不同的概念,但是实现会使得这个语句有时是不真实的。 有时,他们甚至不是你所想的那样。

在Java中,强制执行此规则,而在PHP中,接口是没有声明方法的抽象类。

在Python中,抽象类更像是一种编程技巧,可以从ABC模块中获得,实际上是使用元类,因此也是类。 而且接口与这种语言中的鸭子打字更相关,而且它是公约和调用描述符(__method__方法)的特殊方法之间的混合体。

像编程一样,有另一种语言的理论,实践和实践:-)

抽象类和接口之间的关键技术差异是:

  • 抽象类可以有常量,成员,方法存根(没有主体的方法)和已定义的方法 ,而接口只能有常量方法存根

  • 抽象类的方法和成员可以用任何可见性定义,而接口的所有方法都必须定义为public (它们是默认定义的)。

  • 当inheritance抽象类时, 具体的子类必须定义抽象方法 ,而抽象类可以扩展另一个抽象类,而不必定义父类的抽象方法。

  • 同样,扩展另一个接口的接口也不负责从父接口实现方法 。 这是因为接口不能定义任何实现。

  • 一个子类只能扩展一个类 (抽象或具体),而一个接口可以扩展或一个类可以实现多个其他接口

  • 子类可以定义具有相同或较less限制性的可见性的抽象方法,而实现接口的类必须定义具有完全相同可见性(public)的方法。

一个接口只包含定义/签名的function,如果我们有一些共同的function以及共同的签名,那么我们需要使用一个抽象类。 通过使用抽象类,我们可以同时提供行为和function。 另一个inheritance抽象类的开发人员可以很容易地使用这个function,因为他们只需要填空。

在这里输入图像描述

取自:

http://www.dotnetbull.com/2011/11/difference-between-abstract-class-and.html

http://www.dotnetbull.com/2011/11/what-is-abstract-class-in-c-net.html http://www.dotnetbull.com/2011/11/what-is-interface-in -C-net.html

可以在这里find一个解释: http : //www.developer.com/lang/php/article.php/3604111/PHP-5-OOP-Interfaces-Abstract-Classes-and-the-Adapter-Pattern.htm

抽象类是只由程序员部分实现的类。 它可能包含一个或多个抽象方法。 抽象方法只是一个函数定义,用来告诉程序员该方法必须在子类中实现。

一个接口类似于一个抽象类; 确实接口占据与类和抽象类相同的名称空间。 出于这个原因,你不能定义一个与类相同的接口。 一个接口是一个完全抽象的类; 它的方法没有一个是实现的,而是从它的子类分类,它被认为是实现该接口。

无论如何,我觉得这个接口的解释有些混乱。 一个更常见的定义是: 接口定义了实现类必须履行的契约。 接口定义由公共成员的签名组成,没有任何实现代码。

一些重要的区别:

以表的forms:

区别

正如来自javapapers的Joe所述 :

主要区别在于Java接口的方法是隐式抽象的,不能实现。 Java抽象类可以有实现默认行为的实例方法。

2.在Java接口中声明的variables默认是final。 抽象类可能包含非最终variables。

3.一个Java接口的成员默认是公共的。 一个Java抽象类可以具有像私有,受保护等类的成员通常的风味。

4.Java界面应该使用关键字“implements”来实现。 Java抽象类应该使用关键字“extends”进行扩展。

5.一个接口只能扩展另一个Java接口,一个抽象类可以扩展另一个Java类并实现多个Java接口。

Java类可以实现多个接口,但是它只能扩展一个抽象类。

7.界面绝对抽象,不能实例化; Java抽象类也不能被实例化,但是如果存在main(),则可以被调用。

8.与java抽象类相比,java接口很慢,因为它需要额外的间接寻址。

我不想强调许多答案中已经提到的差异(关于接口中的variables的公共静态最终修饰符和对受保护抽象类中的私有方法的支持)

简而言之,我想说:

接口:通过多个不相关的对象来实现合同

抽象类:在多个相关对象之间实现相同或不同的行为

从Oracle 文档

考虑使用抽象类如果:

  1. 你想在几个密切相关的类中分享代码。
  2. 您期望扩展抽象类的类具有许多常用的方法或字段,或者需要公共访问修饰符(例如protected和private)。
  3. 您想要声明非静态或非最终字段。

考虑使用接口如果:

  1. 你期望不相关的类将实现你的接口。 例如,许多不相关的对象可以实现Serializable接口。
  2. 您想要指定特定数据types的行为,但不关心谁实现其行为。
  3. 你想利用types的多重inheritance。

抽象类与具体类build立“是”的关系。 界面提供了“具有”类的能力。

如果你正在寻找Java作为编程语言,下面是更多的更新:

Java 8通过提供default方法function在一定程度上缩小了interfaceabstract类之间的差距。 一个接口没有一个方法的实现现在不再有效了。

有关更多详细信息,请参阅此文档页面 。

看看这个SE代码示例的问题来更好地理解。

我应该如何解释一个接口和一个抽象类的区别?

我们再来看看这个问题:

首先让你知道的是1/1和1 * 1结果相同,但并不意味着乘法和除法是相同的。 很明显,他们之间有一些很好的关系,但是你们都不一样。

我会指出主要的差异,其余的已经解释了:

抽象类对build模类层次结构很有用。 乍一看任何要求,我们都清楚究竟要build什么 ,但我们知道要build造什么。 所以你的抽象类是你的基类。

接口对于让其他层次结构或类知道我能做什么是有用的。 而当你说我有能力的时候,你必须有这个能力。 接口将标记为一个类实现相同的function的强制性。

如果要在inheritance层次结构中提供多态行为,请使用抽象类。

当你想要完全不相关的类的多态行为时,使用一个接口。

重点是:

  • 摘要是面向对象的 。 它提供了“对象”应具有的基本数据和/或应该能够执行的function。 它关注的是对象的基本特征:它具有什么以及它能做什么。 因此,从同一个抽象类inheritance的对象共享基本特征(泛化)。
  • 接口是function导向的 。 它定义了对象应该具有的function。 不pipe它是什么对象,只要它能够完成界面中定义的这些function,就没有问题。 它忽略了一切。 对象/类可以包含几个(组)function; 因此一个类可以实现多个接口。

我正在修build一座300层的build筑

build筑的蓝图界面

  • 例如,Servlet(I)

build筑高达200层 – 部分完成 – 抽象

  • 部分实现,例如,generics和HTTP servlet

build筑施工完成 – 混凝土

  • 完整的实现,例如,自己的servlet

接口

  • 我们对执行情况一无所知,只是要求。 我们可以去一个界面。
  • 每种方法都是公开的,并且是默认的抽象
  • 这是一个100%纯粹的抽象类
  • 如果我们宣布公开,我们不能申报私营和保护
  • 如果我们声明抽象,我们不能声明final,static,synchronized,strictfp和native
  • 每个接口都有公共的,静态的和最终的
  • 序列化和瞬态不适用,因为我们不能在接口中创build实例
  • 非易失性,因为它是最终的
  • 每个variables都是静态的
  • 当我们在一个接口中声明一个variables时,我们需要在声明时初始化variables
  • 实例和静态块不允许

抽象

  • 部分实施
  • 它有一个抽象的方法。 另外,它使用混凝土
  • 抽象类方法修饰符没有限制
  • 抽象类variables修饰符没有限制
  • 除抽象外,我们不能声明其他修饰符
  • 没有限制来初始化variables
  • 一个构造函数是不允许的

采取从DurgaJobs网站

没有任何实现的抽象类只是看起来像一个接口; 然而,与抽象类和接口之间的相似之处有很多不同之处。 让我们来解释这两个概念,并比较它们的相似和不同之处。

什么是抽象类?

抽象类是一种特殊的类,不能被实例化。 所以问题是为什么我们需要一个无法实例化的类? 抽象类只是被分类(inheritance)。 换句话说,它只允许其他类从它inheritance,但不能被实例化。 其优点是它为所有的子类强制执行某些层次结构。 简而言之,这是一种强制所有子类inheritance相同层次或标准的契约。

什么是接口?

一个接口不是一个类。 它是由接口这个词定义的实体。 一个接口没有实现; 它只有签名或换句话说,就是没有身体的方法的定义。 作为Abstract类的一个相似之处,它是一个用于为所有子类定义层次结构的契约,或者定义了特定的一组方法及其参数。 它们之间的主要区别是一个类可以实现多个接口,但只能从一个抽象类inheritance。 由于C#不支持多重inheritance,接口被用来实现多重inheritance。

一起

当我们创build一个接口时,我们基本上是创build了一组方法,而没有任何必须被实现的类重写的实现。 其优点是它为类提供了一个方法,使其成为两个类的一部分:一个来自inheritance层次结构,另一个来自接口。

当我们创build一个抽象类时,我们正在创build一个可能有一个或多个已完成方法的基类,但是至less有一个或多个方法未完成并被声明为抽象类。 如果抽象类的所有方法都未完成,那么它与接口一样。 抽象类的目的是为一组派生类提供一个基类定义,然后允许程序员在派生类中填充实现。


界面和抽象类有一些相似之处和不同之处。 在这里输入图像描述

实际上这很简单。

你可以把接口想象成只允许有抽象方法的类,而不是别的。

所以一个接口只能“声明”而不能定义你希望类所具有的行为。

抽象类允许你同时声明(使用抽象方法)和定义(使用完整的方法实现)你想要类的行为。

而一个普通的类只允许你定义,而不是声明你希望类所具有的行为/动作。

最后一件事,

在Java中,您可以实现多个接口,但只能扩展一个(抽象类或类)…

这意味着定义行为的inheritance被限制为只允许每个类一个…也就是说,如果你想要一个封装A,B和C类行为的类,你需要做以下的事情:A类扩展B,C类扩展A ..它有一个关于多重inheritance的方法

接口另一方面,你可以简单地做到:接口C实现A,B

所以实际上Java只支持“声明的行为”,即接口的多重inheritance,只有单一的inheritance与定义的行为..除非你绕着我描述的方式…

希望这是有道理的。

在PHP的Interface VS抽象类中可以find一个解释。

结论

抽象类用于共享函数。 接口被用来分享你如何做某事。

界面和抽象类有什么区别?

抽象类

  • 对于抽象类,必须将方法声明为抽象类。 抽象方法没有实现。

  • 抽象方法可以使用Access修饰符来声明,如public,internal,protected等。在子类中实现这些方法时,必须使用相同的(或更less限制的)可见性来定义它们。

  • 抽象类可以包含variables和具体的方法。

  • 一个类只能inheritance一个Abstract类

  • 多重inheritance对于Abstract类是不可能的。

接口

  • 对于一个接口来说,所有的方法默认都是抽象的。 所以不能在接口中声明variables或具体的方法。

  • 在接口中声明的所有方法都必须是公共的。

  • 除了常量外,接口不能包含variables和具体的方法。

  • 一个类可以实现多个接口

  • 多接口inheritance是可能的。

唯一的区别是可以参与多重inheritance,其他不可以。

界面的定义随着时间而改变。 你认为一个接口只有方法声明,只是合同吗? 静态最终variables和Java 8之后的默认定义呢?

接口被引入到Java,因为多重inheritance的钻石问题 ,这就是他们实际打算做的。

接口是为了摆脱多inheritance问题而创build的结构,可以有抽象方法,默认定义和静态最终variables。

请参阅为什么Java在接口中仅允许使用静态最终variables?

界面与抽象类的比较是错误的。 应该有另外两个比较:1) 接口与类和2) 抽象与最终类

接口与类

接口是两个对象之间的契约。 例如,我是邮递员,你是一个包裹交付。 我希望你知道你的送货地址。 当有人给我一个套餐,它必须知道它的送货地址:

 interface Package { String address(); } 

是一组服从合同的对象。 例如,我是“箱子”组的一个箱子,我服从邮递员所要求的合同。 同时我也服从其他合同:

 class Box implements Package, Property { @Override String address() { return "5th Street, New York, NY"; } @Override Human owner() { // this method is part of another contract } } 

摘要vs决赛

抽象类是一组不完整的对象。 他们不能使用,因为他们错过了一些部分。 例如,我是一个抽象的GPS感知框 – 我知道如何检查我在地图上的位置:

 abstract class GpsBox implements Package { @Override public abstract String address(); protected Coordinates whereAmI() { // connect to GPS and return my current position } } 

这个类,如果被另一个类inheritance/扩展,可能是非常有用的。 但是,由于它本身没有对象,所以它本身是无用的。 抽象类可以构build最终类的元素。

末class是一组完整的对象,可以使用,但不能修改。 他们知道如何工作和做什么。 例如,我是一个箱子,它总是在施工过程中指定的地址:

 final class DirectBox implements Package { private final String to; public DirectBox(String addr) { this.to = addr; } @Override public String address() { return this.to; } } 

在大多数语言中,像Java或C ++,都可能只有一个类 ,既不是抽象的,也不是最终的。 这样的类可以被inheritance并且可以被实例化。 不过,我认为这不完全符合面向对象的范式。

再次,比较接口和抽象类是不正确的。

界面:转(左转,右转)

抽象类:轮子。

类:方向盘,从车轮派生,暴露界面转向

一个是对可以跨越多种事物提供的行为进行分类,另一个是对事物的本体论进行build模。

总之,区别如下:

接口抽象类之间的语法差异:

  1. 抽象类的方法和成员可以具有任何可见性。 接口的所有方法都必须是公共的//不再适用于Java 9
  2. 抽象类的具体子类必须定义所有的抽象方法。 一个抽象的子类可以有抽象的方法。 扩展另一个接口的接口不需要为从父接口inheritance的方法提供默认实现。
  3. 一个子类只能扩展一个类。 一个接口可以扩展多个接口。 一个类可以实现多个接口。
  4. 子类可以定义具有相同或更less限制性可见性的抽象方法,而实现接口的类必须将所有接口方法定义为public。
  5. 抽象类可以有构造函数,但不能有接口
  6. 来自Java 9的接口具有私有的静态方法。

在接口现在:

public static – 支持
public abstract – 支持
public default – 支持
private static – 支持
private abstract – 编译错误
private default – 编译错误
private支持

inheritance被用于两个目的:

  • 允许一个对象将父types的数据成员和方法实现视为自己的。

  • 允许引用一种types的对象,以供期望引用超types对象的代码使用。

在支持泛化多重inheritance的语言/框架中,通常很less需要将types分类为“接口”或“抽象类”。 然而,stream行的语言和框架将允许一个types把一个其他types的数据成员或方法实现视为它自己的,尽pipe它们允许一个types可以被任意数量的其他types替代。

抽象类可能有数据成员和方法实现,但只能由不能从其他类inheritance的类inheritance。 接口对实现它们的types几乎没有限制,但不能包含任何数据成员或方法实现。

有些时候,types可以替代许多不同的东西是有用的。 还有一些时候对象将父types数据成员和方法实现视为自己的东西是有用的。 在界面和抽象类之间进行区分可以使这些能力中的每一个在最相关的情况下被使用。

关键点:

  • 抽象类可以有属性,数据字段,方法(完整/不完整)。
  • 如果在抽象关键字中定义的方法或属性必须在派生类中重写(其作为紧耦合的function)
  • 如果为抽象类中的方法或属性定义抽象关键字,则无法为属性定义方法主体和get / set值,并且必须在派生类中重写。
  • 抽象类不支持多重inheritance。
  • 抽象类包含构造函数。
  • 抽象类可以包含对subs,functions,properties的访问修饰符。
  • 只有完全成员的抽象类可以是静态的。
  • 一个接口只能从另一个接口inheritance,不能从一个抽象类inheritance,而抽象类可以从另一个抽象类或另一个接口inheritance。

优点:

  • 这是一种迫使所有的亚类inheritance相同的等级或标准的合同。
  • 如果各种实现是相同types的并且使用普通的行为或状态,那么抽象类更好用。
  • 如果我们为抽象类添加一个新方法,那么我们可以select提供默认实现,因此所有现有的代码都可以正常工作。
  • 它允许比接口快速的执行(接口需要更多的时间在相应的类中find实际的方法)
  • 它可以用于紧密和松散的耦合。

在这里find细节… http://pradeepatkari.wordpress.com/2014/11/20/interface-and-abstract-class-in-c-oops/

在这里输入图像描述

这是对接口和抽象类的一个非常基本的理解。

Not really the answer to the original question, but once you have the answer to the difference between them, you will enter the when-to-use-each dilemma: When to use interfaces or abstract classes? When to use both?

I've limited knowledge of OOP, but seeing interfaces as an equivalent of an adjective in grammar has worked for me until now (correct me if this method is bogus!). For example, interface names are like attributes or capabilities you can give to a class, and a class can have many of them: ISerializable, ICountable, IList, ICacheable, IHappy, …

The shortest way to sum it up is that an interface is:

  1. Fully abstract, apart from default and static methods; while it has definitions (method signatures + implementations) for default and static methods, it only has declarations (method signatures) for other methods.
  2. Subject to laxer rules than classes (a class can implement multiple interface s, and an interface can inherit from multiple interface s). All variables are implicitly constant, whether specified as public static final or not. All members are implicitly public , whether specified as such or not.
  3. Generally used as a guarantee that the implementing class will have the specified features and/or be compatible with any other class which implements the same interface.

Meanwhile, an abstract class is:

  1. Anywhere from fully abstract to fully implemented, with a tendency to have one or more abstract methods. Can contain both declarations and definitions, with declarations marked as abstract .
  2. A full-fledged class, and subject to the rules that govern other classes (can only inherit from one class), on the condition that it cannot be instantiated (because there's no guarantee that it's fully implemented). Can have non-constant member variables. Can implement member access control, restricting members as protected , private , or private package (unspecified).
  3. Generally used either to provide as much of the implementation as can be shared by multiple subclasses, or to provide as much of the implementation as the programmer is able to supply.

Or, if we want to boil it all down to a single sentence: An interface is what the implementing class has , but an abstract class is what the subclass is .

Many junior developers make the mistake of thinking of interfaces, abstract and concrete classes as slight variations of the same thing, and choose one of them purely on technical grounds: Do I need multiple inheritance? Do I need some place to put common methods? Do I need to bother with something other than just a concrete class? This is wrong, and hidden in these questions is the main problem: "I" . When you write code for yourself, by yourself, you rarely think of other present or future developers working on or with your code.

Interfaces and abstract classes, although apparently similar from a technical point of view, have completely different meanings and purposes.

概要

  1. An interface defines a contract that some implementation will fulfill for you .

  2. An abstract class provides a default behavior that your implementation can reuse.

Alternative summary

  1. An interface is for defining public APIs
  2. An abstract class is for internal use, and for defining SPIs

On the importance of hiding implementation details

A concrete class does the actual work, in a very specific way. For example, an ArrayList uses a contiguous area of memory to store a list of objects in a compact manner which offers fast random access, iteration, and in-place changes, but is terrible at insertions, deletions, and occasionally even additions; meanwhile, a LinkedList uses double-linked nodes to store a list of objects, which instead offers fast iteration, in-place changes, and insertion/deletion/addition, but is terrible at random access. These two types of lists are optimized for different use cases, and it matters a lot how you're going to use them. When you're trying to squeeze performance out of a list that you're heavily interacting with, and when picking the type of list is up to you, you should carefully pick which one you're instantiating.

On the other hand, high level users of a list don't really care how it is actually implemented, and they should be insulated from these details. Let's imagine that Java didn't expose the List interface, but only had a concrete List class that's actually what LinkedList is right now. All Java developers would have tailored their code to fit the implementation details: avoid random access, add a cache to speed up access, or just reimplement ArrayList on their own, although it would be incompatible with all the other code that actually works with List only. That would be terrible… But now imagine that the Java masters actually realize that a linked list is terrible for most actual use cases, and decided to switch over to an array list for their only List class available. This would affect the performance of every Java program in the world, and people wouldn't be happy about it. And the main culprit is that implementation details were available, and the developers assumed that those details are a permanent contract that they can rely on. This is why it's important to hide implementation details, and only define an abstract contract. This is the purpose of an interface: define what kind of input a method accepts, and what kind of output is expected, without exposing all the guts that would tempt programmers to tweak their code to fit the internal details that might change with any future update.

An abstract class is in the middle between interfaces and concrete classes. It is supposed to help implementations share common or boring code. For example, AbstractCollection provides basic implementations for isEmpty based on size is 0, contains as iterate and compare, addAll as repeated add , and so on. This lets implementations focus on the crucial parts that differentiate between them: how to actually store and retrieve data.

APIs versus SPIs

Interfaces are low-cohesion gateways between different parts of code. They allow libraries to exist and evolve without breaking every library user when something changes internally. It's called Application Programming Interface , not Application Programming Classes. On a smaller scale, they also allow multiple developers to collaborate successfully on large scale projects, by separating different modules through well documented interfaces.

Abstract classes are high-cohesion helpers to be used when implementing an interface, assuming some level of implementation details. Alternatively, abstract classes are used for defining SPIs, Service Provider Interfaces.

The difference between an API and an SPI is subtle, but important: for an API, the focus is on who uses it, and for an SPI the focus is on who implements it.

Adding methods to an API is easy, all existing users of the API will still compile. Adding methods to an SPI is hard, since every service provider (concrete implementation) will have to implement the new methods. If interfaces are used to define an SPI, a provider will have to release a new version whenever the SPI contract changes. If abstract classes are used instead, new methods could either be defined in terms of existing abstract methods, or as empty throw not implemented exception stubs, which will at least allow an older version of a service implementation to still compile and run.

A note on Java 8 and default methods

Although Java 8 introduced default methods for interfaces, which makes the line between interfaces and abstract classes even blurrier, this wasn't so that implementations can reuse code, but to make it easier to change interfaces that serve both as an API and as an SPI (or are wrongly used for defining SPIs instead of abstract classes).

Which one to use?

  1. Is the thing supposed to be publicly used by other parts of the code, or by other external code? Add an interface to it to hide the implementation details from the public abstract contract, which is the general behavior of the thing.
  2. Is the thing something that's supposed to have multiple implementations with a lot of code in common? Make both an interface and an abstract, incomplete implementation.
  3. Is there ever going to be only one implementation, and nobody else will use it? Just make it a concrete class.
    1. "ever" is long time, you could play it safe and still add an interface on top of it.

A corollary: the other way around is often wrongly done: when using a thing , always try to use the most generic class/interface that you actually need. In other words, don't declare your variables as ArrayList theList = new ArrayList() , unless you actually have a very strong dependency on it being an array list, and no other type of list would cut it for you. Use List theList = new ArrayList instead, or even Collection theCollection = new ArrayList if the fact that it's a list, and not any other type of collection doesn't actually matter.

By definition, interfaces cannot have an implementation for any methods, and member variables cannot be initialized.

However, abstract classes can have methods implementated and member variables initialized.

Use abstract classes when you expect changes in your contract, ie, say in future you might need to add a new method.

In this situation, if you decide to use an interface, when the interface is changed to include interface, your application will break when you dumped the new interface dll.

To read in detail, visit difference between abstract class and a interface

I'd like to add one more difference which makes sense. For example, you have a framework with thousands of lines of code. Now if you want to add a new feature throughout the code using a method enhanceUI(), then it's better to add that method in abstract class rather in interface. Because, if you add this method in an interface then you should implement it in all the implemented class but it's not the case if you add the method in abstract class.

Differences between abstract class and interface on behalf of real implementation.

Interface : It is a keyword and it is used to define the template or blue print of an object and it forces all the sub classes would follow the same prototype,as for as implementation, all the sub classes are free to implement the functionality as per it's requirement.

Some of other use cases where we should use interface.

Communication between two external objects(Third party integration in our application) done through Interface here Interface works as Contract.

Abstract Class: Abstract,it is a keyword and when we use this keyword before any class then it becomes abstract class.It is mainly used when we need to define the template as well as some default functionality of an object that is followed by all the sub classes and this way it removes the redundant code and one more use cases where we can use abstract class , such as we want no other classes can directly instantiate an object of the class, only derived classes can use the functionality.

Example of Abstract Class:

  public abstract class DesireCar { //It is an abstract method that defines the prototype. public abstract void Color(); // It is a default implementation of a Wheel method as all the desire cars have the same no. of wheels. // and hence no need to define this in all the sub classes in this way it saves the code duplicasy public void Wheel() { Console.WriteLine("Car has four wheel"); } } **Here is the sub classes:** public class DesireCar1 : DesireCar { public override void Color() { Console.WriteLine("This is a red color Desire car"); } } public class DesireCar2 : DesireCar { public override void Color() { Console.WriteLine("This is a red white Desire car"); } } 

Example Of Interface:

  public interface IShape { // Defines the prototype(template) void Draw(); } // All the sub classes follow the same template but implementation can be different. public class Circle : IShape { public void Draw() { Console.WriteLine("This is a Circle"); } } public class Rectangle : IShape { public void Draw() { Console.WriteLine("This is a Rectangle"); } } 

You can find clear difference between interface and abstract class.

接口

  • Interface only contains abstract methods.
  • Force users to implement all methods when implements the interface.
  • Contains only final and static variables.
  • Declare using interface keyword.
  • All methods of an interface must be defined as public.
  • An interface can extend or a class can implement multiple other interfaces.

Abstract class

  • Abstract class contains abstract and non-abstract methods.

  • Does not force users to implement all methods when inherited the abstract class.

  • Contains all kinds of variables including primitive and non-primitive

  • Declare using abstract keyword.

  • Methods and members of an abstract class can be defined with any visibility.

  • A child class can only extend a single class (abstract or concrete).

If you have some common methods that can be used by multiple classes go for abstract classes. Else if you want the classes to follow some definite blueprint go for interfaces.

Following examples demonstrate this.

Abstract class in Java:

 abstract class animals { // They all love to eat. So let's implement them for everybody void eat() { System.out.println("Eating..."); } // The make different sounds. They will provide their own implementation. abstract void sound(); } class dog extends animals { void sound() { System.out.println("Woof Woof"); } } class cat extends animals { void sound() { System.out.println("Meoww"); } } 

Following is an implementation of interface in Java:

 interface Shape { void display(); double area(); } class Rectangle implements Shape { int length, width; Rectangle(int length, int width) { this.length = length; this.width = width; } @Override public void display() { System.out.println("****\n* *\n* *\n****"); } @Override public double area() { return (double)(length*width); } } class Circle implements Shape { double pi = 3.14; int radius; Circle(int radius) { this.radius = radius; } @Override public void display() { System.out.println("O"); // :P } @Override public double area() { return (double)((pi*radius*radius)/2); } } 

Some Important Key points in a nutshell:

  1. The variables declared in Java interface are by default final. Abstract classes can have non-final variables.

  2. The variables declared in Java interface are by default static. Abstract classes can have non-static variables.

  3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..

Interfaces are generally the classes without logic just a signature. Whereas abstract classes are those having logic. Both support contract as interface all method should be implemented in the child class but in abstract only the abstract method should be implemented. When to use interface and when to abstract? Why use Interface?

 class Circle { protected $radius; public function __construct($radius) { $this->radius = $radius } public function area() { return 3.14159 * pow(2,$this->radius); // simply pie.r2 (square); } } //Our area calculator class would look like class Areacalculator { $protected $circle; public function __construct(Circle $circle) { $this->circle = $circle; } public function areaCalculate() { return $circle->area(); //returns the circle area now } } 

We would simply do

 $areacalculator = new Areacalculator(new Circle(7)); 

Few days later we would need the area of rectangle, Square, Quadrilateral and so on. If so do we have to change the code every time and check if the instance is of square or circle or rectangle? Now what OCP says is CODE TO AN INTERFACE NOT AN IMPLEMENTATION. Solution would be:

 Interface Shape { public function area(); //Defining contract for the classes } Class Square implements Shape { $protected length; public function __construct($length) { //settter for length like we did on circle class } public function area() { //return l square for area of square } Class Rectangle implements Shape { $protected length; $protected breath; public function __construct($length,$breath) { //settter for length, breath like we did on circle,square class } public function area() { //return l*b for area of rectangle } } 

Now for area calculator

 class Areacalculator { $protected $shape; public function __construct(Shape $shape) { $this->shape = $shape; } public function areaCalculate() { return $shape->area(); //returns the circle area now } } $areacalculator = new Areacalculator(new Square(1)); $areacalculator->areaCalculate(); $areacalculator = new Areacalculator(new Rectangle(1,2)); $areacalculator->;areaCalculate(); 

Isn't that more flexible? If we would code without interface we would check the instance for each shape redundant code.

Now when to use abstract?

 Abstract Animal { public function breathe(){ //all animals breathe inhaling o2 and exhaling co2 } public function hungry() { //every animals do feel hungry } abstract function communicate(); // different communication style some bark, some meow, human talks etc } 

Now abstract should be used when one doesn't need instance of that class, having similar logic, having need for the contract.