How to Have Explained the Difference Between an Interface and an Abstract Class

What is the difference between an interface and abstract class?

Interfaces

An interface is a contract: The person writing the interface says, "hey, I accept things looking that way", and the person using the interface says "OK, the class I write looks that way".

An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.

For example (pseudo code):

// 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;
}
}

Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices.


Abstract classes

Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them.

Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, "these classes should look like that, and they have that in common, so fill in the blanks!".

For example:

// 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");
}
}

Implementation

While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are.

In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared.

In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods).

As usual with programming, there is theory, practice, and practice in another language :-)

Fundamental difference between interface and abstract class in Java 8

Interfaces still can't have any state. Interfaces still can't have any final method, which means that any implementation can override all its default methods. And interfaces still can't have any constructor.

You can still implement multiple interfaces, even if they have default methods with the same signature. You can't extend multiple classes (abstract or not).

How can you explain the difference between an interface and an abstract class to a non-programmer?

The player Interface

In my Java courses I often use this interface kind of image and ask: "What is this ?"

Every time someone will say "that's a player". From this image you can teach anybody what an interface is. This Interface allow any user to "play" something. Everybody knows what these buttons mean, even if you don't know what exactly will be done, you can use anything with this interface and you know that the little arrow will "play" and other arrows will probably send you forward or backward.
Everything that will have those buttons will provide a standard behavior that any user will know before even starting to use them.

I usually try to avoid the "contract" word which can be misunderstood.

The DVD player Abstract class

And then from the Play Interface, I go to the VCR (or DVD) player. Every constructor of DVD player must add some special functions to transform a simple unknown player into a DVD player. For example the eject button. And they must correctly implement Player.

The play button will launch the content of the DVD.

But even if DVD Player provide the basic behavior of a DVD player, not everything is done. You can't simply have "a" DVD player, it has a brand and most of the time it has its own firmware. A this time you'll need to extend the DVD Player abstract class to add your own little components.

Difference between abstract class with all method abstract and interface?

The answer stating that an interface represents a contract is not acceptable.
That's the answer we give to Junior since it may be too complex to clearly figure out the difference between the essence of an abstract class and the essence of an interface without much architecture experience and without reading a lot of classic books about.
Any abstract class with public methods acts as a contract, as well as an interface.

An abstract class that doesn't provide any implementation is in 99% of cases a representation of an object's Role.

An interface represents a Role.

Each object might have several different roles that shouldn't be tied together but composed by the concerned object.

I'm explaining this with this example:

Your interviewer could say:

I have a Robot that can walk and a Human that can walk too.

So based on this case, he asks you: should I extract the walking feature in an abstract base class or in an interface, knowing that the implementations have nothing in common?

You think..."oh I know so: in this case, having one abstract class with an abstract method walk(), then is clearly the same than declaring an interface with the walk() method."

So your answer would surely be: "it's the choice of the developer !".

And it's really not an always valid answer.

Why? Let's see the next expectation:

A Human can eat, but obviously the Robot cannot and even doesn't need.

What if you implemented the walking feature with an abstract class? You would end up with:

public abstract class Biped {  
public void abstract walk();
}

public Robot extends Biped {
public void walk() {
//walk at 10km/h speed
}
}

public Human extends Biped {
public void walk() {
//walk at 5km/h speed
}
}

How could you plug the eating feature? You're stuck because you can't implement it in the Biped base class since it would break Liskov Substitution Principle, since a Robot doesn't eat!
And you can't expect Human extending another base class due to the known Java rule.

Of course, you could add a specific Feedable interface only dedicated to Human:

public interface Feedable {
void eat();
}

Signature becomes: public Human extends Biped implements Feedable {
Clearly, it makes no sense and confusing to have one role implemented through a class and the other through an interface.

That's why starting with interface is really preferred whenever we have the choice.

With an interface, we can model Roles easily by composing.

So the final solution would then be:

public interface Walkable {
void abstract walk();
}

public interface Feedable {
void eat();
}

public Robot implements Walkable {
public void walk() {
//walk at 10km/h speed
}
}

public Human implements Walkable, Feedable {
public void walk() {
//walk at 5km/h speed
}

public void eat(){
//...
}
}

Doesn't it remind you the Interface Segregation Principle? ;)

To sum up, if you specify an IS-A relationship, uses an abstract class.
If you realize that you are about to model a Role (let's say a IS-CAPABLE-OF relationship), go with interface.

What's the difference between an abstract class and an interface?

There are technical differences between Abstract Classes and Interfaces, that being an Abstract Class can contain implementation of methods, fields, constructors, etc, while an Interface only contains method and property prototypes. A class can implement multiple interfaces, but it can only inherit one class (abstract or otherwise).

However, in my opinion, the most important difference between Interfaces and Abstract Classes is the semantic difference.

An Interface defines what something can do (how it behaves), and an Abstract Class defines what something is.

Take for example IEnumerable, the semantic meaning behind this is that anything that implements IEnumerable is enumerable, it doesn't mean that it's an enumeration, but that it can behave like one (can be enumerated).

Contrast that with a washing machine example, anything that inherits it is a type of washing machine. Anything that inherits it would be a type of washing machine, a top loader, or side loader, etc.

Instead, if you had an interface called ICanWash, which could contain a method called Wash. You could have various things implement ICanWash, be it a Person, an abstract washing machine class, etc, where the actual implementation does not matter, just you need to know that the behavior is that it can wash things.

In summary, classes define what something is, interfaces define what something can do.

What is the difference between interface and abstract class in Typescript?

Interfaces

An interface is a contract that defines the properties and what the object that implements it can do. For example, you could define what can do a Plumber and an Electrician:

interface Electrician {
layWires(): void
}

interface Plumber {
layPipes(): void
}

Then, you can consume the services of your interfaces:

function restoreHouse(e: Electrician, p: Plumber) {
e.layWires()
p.layPipes()
}

Notice that the way you have to implement an interface is free. You can do that by instantiating a class, or with a simple object:

let iAmAnElectrician = {
layWires: () => { console.log("Work with wires…") }
}

An interface doesn't exist at all at runtime, so it is not possible to make an introspection. It is the classic JavaScript way to deal with object programming, but with a good control at compile time of the defined contracts.

Abstract classes

A class is both a contract and the implementation of a factory. An abstract class is also an implementation but incomplete. Especially, an abstract class exists at runtime, even if it has only abstract methods (then instanceof can be used).

When you define an abstract class, you often try to control how a process has to be implemented. For example, you could write something like this:

abstract class HouseRestorer {
protected abstract layWires(): void
protected abstract layPipes(): void
restoreHouse() {
this.layWires()
this.layPipes()
}
}

This abstract class HouseRestorer defines how the methods layWires and layPipes will be used, but it is up to a child class to implement the specialized treatments before it can be used.

Abstract classes are a traditional OOP approach, which is not traditional in JavaScript.

Both approaches allow the same things to be done. They are two different ways of solving a problem.



Related Topics



Leave a reply



Submit