Java Q & A Blog

August 24, 2008

Why the use on interfaces instead of abstract classes, is encouraged in java programming?

Filed under: Architect, Sr. Developer — Devesh S N Bhatta @ 7:41 pm

There is two thing is in Architect’s mind when designing classes.
1. Behavior of an object .
2. object’s implementation.

If an entity has more than one implementation ,then separating the behavior of an object from its implementation is one of the key for maintainability and decoupling.
Separation can be achieved by either Abstract class or Interface but which one is the best? Lets take an example to check this.

Lets take a development scenario where things (request, class model etc) are changing very frequently and you have to deliver certain versions of application.

Initial problem statement : you have to create a “Train” class for Indian railway which has behavior of maxSpeed in 1970 .

1. Business Modeling with abstract class

==V 0.0 (Initial problem)==
Initial problem statement : you have to create a “Train” class for Indian railway which has behavior of maxSpeed in 1970 .

public abstract class Train {
public int maxSpeed();
}

==V 1.0 (Changed problem 1)==
chanded problem statement : You have to create a “Diesel Train” class for Indian railway which has behavior of maxSpeed ,in 1975.

public abstract class DieselTrain extends train {
public int maxFuelCapacity ();
}

==V 2.0 (Changed problem 2)==
chanded problem statement : you have to create a “Electrical Train” class for Indian railway which has behavior of maxSpeed , maxVoltage in 1980.

public abstract class ElectricalTrain extends train {
public int maxvoltage ();
}

==V 3.0 (Changed problem 3 )==

chanded problem statement : you have to create a “Hybrid Train ” (uses both diesel and electrcity) class for Indian railway which has behavior of maxSpeed , maxVoltage,maxVoltage in 1985 .

public abstract class HybridTrain extends ElectricalTrain , DisealTrain
{
{Not possible in java}
}
{here Business modeling with abstract class fails}

2. Business Modeling with interface

Just change “abstract” word to “interface” and  ……
your Business Modeling with interface will succeeds.


That’s Why use of interfaces instead of abstract classes, is encouraged in java programming.

About these ads

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Shocking Blue Green Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: