When to use an interface instead of an abstract cl

2018-12-31 07:01发布

This may be a generic OOP question. I wanted to do a generic comparison between an interface and an abstract class on the basis of their usage.

When would one want to use an interface and when would one want to use an abstract class?

22条回答
零度萤火
2楼-- · 2018-12-31 07:29

An abstract class can have implementations.

An interface doesn't have implementations, it simply defines a kind of contract.

There can also be some language-dependent differences: for example C# does not have multiple inheritance, but multiple interfaces can be implemented in a class.

查看更多
几人难应
3楼-- · 2018-12-31 07:32

I wrote an article about that:

Abstract classes and interfaces

Summarizing:

When we talk about abstract classes we are defining characteristics of an object type; specifying what an object is.

When we talk about an interface and define capabilities that we promise to provide, we are talking about establishing a contract about what the object can do.

查看更多
查无此人
4楼-- · 2018-12-31 07:32

This can be a very difficult call to make...

One pointer I can give: An object can implement many interfaces, whilst an object can only inherit one base class( in a modern OO language like c#, I know C++ has multiple inheritance - but isn't that frowned upon?)

查看更多
素衣白纱
5楼-- · 2018-12-31 07:34

Basic thumb rule is: For "Nouns" use Abstract class and for "Verbs" use interface

E.g: car is an abstract class and drive, we can make it an interface.

查看更多
何处买醉
6楼-- · 2018-12-31 07:35

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. 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).
  3. 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:

  1. You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
  2. You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
  3. You want to take advantage of multiple inheritances.

Source

查看更多
路过你的时光
7楼-- · 2018-12-31 07:36

An abstract class can have shared state or functionality. An interface is only a promise to provide the state or functionality. A good abstract class will reduce the amount of code that has to be rewritten because it's functionality or state can be shared. The interface has no defined information to be shared

查看更多
登录 后发表回答