Thursday, April 15, 2010

Abstract Class Vs Interface

I had a recent interaction with one experienced java person and he asked me a simple question "When do u think we should use Abstract classes and when we should use interfaces".

The question seemed to be trivial and i came up with standard answers like interfaces support multiple inheritance and it makes our code debugging easier, abstract class can declare a non abstract method also. So it depends on the requirement.

But these are all java theory concepts and the question is more about java designing.
Yes its true that it depends upon requirement but the point is how to analyse the requirement for the use for interface or abstract class.

Lets take an example go into more details.
A company manufactures various kinds of clocks and it wants to develop a software so that it get details clock.

1st approach using Interface : An interface by the name clock is created which defines a method "getTime()". Now they have different types of clock like mechanical , electronic etc, so they extend this interface and create MechanicalClock , ElectronicClock interfaces etc. Code was tested and debugging was done and everything was working fine and suddenly a requirement come up that customer also requires an API to get seconds also.
In order to add requirement if you change your interface then everything break and all the classes will have to modified again. This can be very expensive as whole of testing of a stable code will have to done again.

2 approach using Abstract class : If we implement the above scenario using abstract class, our job will be extremely simple. We just have add another non abstract method "getSeconds" in our abstract class and all classes can call it. So job done without any headache.

Its clear that in above scenario we should use AbstractClass.

Let us modify the above scenario. Now company makes a clock which is combination both mechanical and electronic clock.
Now if we have used AbstractClass implementation we are struck and only way out is lots of special case changes or re implemnting the whole hierarchy as java doesn't support multiple inheritance.
Implementation using interface will score out here as we can create a new interface extending MechanicalInterface and ElectronicInterface reason being interface support multiple inheritance.

So to summarise if we want an implementation hierarchy where classes may posess some common behaviour implementation then AbstractClass is the way to go. But if we are not going to maintain an implmentation hierarchy and we might need to combine some unrelated classes in our implementation then interfaces will be better choice.

This decision is very important as a good design forms the base of a good software.

No comments: