Thursday, January 10, 2008

Again Abstract class vs Interface...

While pairing with a fellow thoughtworker (http://thoughtworker.in) we ended up discussing Abstract class vs Interface and he found this explanation useful.

A Class (abstract or not) defines a type while an interface does not.

In my domain anything that can be drawn is a shape(including a point) and thus behaviour defines a type.

abstract class Shape
{
public abstract draw();
}

In another domain which includes a Robots, Humans and Pets,
If I need to treat all objects that can walk similarly, I would like to have an abstract handle to of all the above and that ends up in a

interface Walkable{

void walk();

}

...Robot implements Walkable{...}
...Human implements Walkable{...}
...Pet implements Walkable{...}

and merely something that can walk does not define a type here. Its a mechanism to tie together otherwise unrelated types Robot, Human and Pet.

8 comments:

Luix said...

This is the best explanation that I ever read.

Nat Pryce said...

Of course an interface defines a type.

Ankit Jain said...

I am little confused. just wanted to know if we cannot say "walk" as a behavior/type?

Kalpesh said...

Nice explanation. I was asked this in one interview ;)

To which I said, an interface defines a contract which needs to be implemented by the agreeing party.

Abstract classes are classes for which some/all of the behaviour cannot be defined. So, an abstract class can have some concrete behaviour (method). But, classes are abstract when they cannot define a concrete behaviour for something & wants the inheritors to be providing implementation.

Felix said...
This post has been removed by the author.
Felix said...

I am all with Nat. Interfaces surely define types. To come to a better answer to the abstract class vs interface question I would like to challenge your assumption that everything in your domain that can be drawn is a Shape. Why isn't it a Drawable instead?

Kalpesh said...

Felix has a point. However, choice of whether to use abstract class or interface also depends on the domain.

For e.g. Shape -> Circle, Rectangle might have relevance to the domain.

Having an Area method is more relevant. Also, everything drawable might not have Area

So, Shape can define Area method, which Circle or Rectangle has to provide its implementation

Like I said in my previous comment,
"Abstract classes are classes for which some/all of the behaviour cannot be defined. So, an abstract class can have some concrete behaviour (method)."

Aslam's Blog said...

Every solution is designed for a domain and ofcourse has a defined scope. So is my example.

Why Shape is an abstract class? Because I cannot think of anything that is Drwable and is not a Shape. Can you please give me an example of a Drawable which is not a Shape?

'Type' is used as in real world type.