Abstract class or interface. Which way is right?

There are two ways to choose between an abstract class or interface. Microsoft Solution and Oracle Solution:


Microsoft Design Guide:

Use abstract classes (MustInherit in Visual Basic) instead of interfaces to decouple the contract with implementations.

http://msdn.microsoft.com/en-us/library/ms229013.aspx


Oracle Java Tutorials:

If an abstract class contains only declarations of an abstract method, it should be declared as an interface.

http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html


My question is which way is right? Microsoft or Oracle solution? Please note that I think that the choice between an abstract class or interface should not depend on the programming language (Java or C #).

+8
java c # interface abstract-class
source share
3 answers

If I remember my blog correctly, Microsoftโ€™s advice on using abstract classes stems from the ability to reuse implementations with an abstract class, which you cannot do with the interface.

Please note that the Microsoft page you are linking to is a specific guide for writing code libraries for sharing / reuse in multiple projects. The probability in this situation is that you yourself will write all the implementations of the interface, possibly within the same assembly. Good practices for working with a single product or system may vary slightly.

One general approach I've seen across multiple codebases in multiple languages โ€‹โ€‹is this:

  • Define an interface for specifying a contract
  • Create an abstract class that implements the contract to provide any common implementation that is useful to all descendants.
  • Contract implementations then have the option to start with a base class for convenience or simply implement an interface if they want complete control

The fourth step common in the .NET world is to provide advanced extension functions built on the interface.

+10
source share

These are two operators for different contexts.

The Microsoft recommendation you are quoting is for Designing Class Library Classes. And it talks about giving preference to abstract classes: you can add functionality without breaking anything.

Microsoft also advises interfaces for the separation and decoupling of levels and other boundaries.

+7
source share

The interface has no implementation - this is a contract. This allows you to completely unleash.

I will move from an interface to an abstract (base) class if I want to provide some general implementation, while forcefully inheriting a class of the class of the inherited class to provide some implementation specific to this class. This provides less isolation.

Also keep in mind that many languages, such as C # (and .net, such as VB.net, etc.), as well as Java, do not allow multiple inheritance, so interfaces become a way to allow a class to have many behaviors.

+1
source share

All Articles