Welcome!

Java Authors: Roger Strukhoff, Pat Romanski, Elizabeth White, Yeshim Deniz, Jackie Kahle

Related Topics: Java

Java: Article

Interfaces Vs Abstract Classes In Java

Interfaces Vs Abstract Classes In Java

Have you ever wondered why you should use interfaces instead of abstract classes, or vice versa? More specifically, when dealing with generalization, have you struggled with using one or the other? I'll shed some light on what can be a very confusing issue.

To start, I'll identify two pieces of the development puzzle: the behavior of an object and the object's implementation.

When designing an entity that can have more than one implementation, the goal is to describe the entity's behavior in such a way that it can be used without knowing exactly how the entity's behavior is implemented. In essence, you're separating the behavior of an object from its implementation. But is this separation best achieved by way of an interface or by way of an abstract class? Both can define methods without saying how they work. So which one do you use?

Modeling Behavior in an Abstract Class
As a rule, pure behavior is always modeled by interfaces and not in abstract classes. This example will model behavior in an abstract class to illustrate why.

Pretend you're designing a "motor" entity for an application that your sales department will use to sell motors. You're not modeling every aspect and nuance of a motor, but instead modeling what's important for the company and the process you're automating. (You find out what's important by talking to the users of a system. In this case it's your sales department. Good luck!)

Your sales department says that every motor has a horsepower rating, and this feature is the only attribute they're concerned with.

Based on this statement, you describe the following behavior of a motor:

Behavior: Someone can ask the motor for its horsepower rating, and the motor will return its rating as an integer.

At this point you don't know where the horsepower comes from, but you do know that this behavior must exist.

Translated into a method signature this behavior becomes:

public int getHorsepower()

Your company has several different types of motors, but given our particular application, this behavior is the only rule that applies to all of them. You look at both interfaces and abstract classes, but for purposes of illustration the motors will be modeled as an abstract class.

public abstract Motor{
abstract public int getHorsepower();
}
You make a handful of concrete implementations of this class, and version 1.0 of the application enters production.

Time passes and you're called to create version 2.0. While reviewing the requirements for the second version, you find that a small subset of motors is battery-powered, and that these batteries take time to recharge. The sales department wants to be able to view the time to recharge from the computer screen. From their statement, you derive a behavior:

Behavior: Someone can ask a battery-powered motor for its time to recharge and the motor will return its time as an integer.

public int getTimeToRecharge();
Translated into a method signature this behavior becomes:
public abstract BatteryPoweredMotor extends Motor{
abstract public int getTimeToRecharge();
}
The new battery-powered motors are implemented inside the application as concrete classes. It's important to note that these classes extend Battery- PoweredMotor as opposed to Motor. The changes are released as version 2 and the sales department is happy once again.

But business is changing, and soon solar-powered motors are introduced. The sales department tells you that solar-powered motors require a minimum amount of light energy to operate. This light energy is measured in lumens. The customers want to know this information. There's a fear that on cloudy days some solar-powered motors won't operate. The sales department requests that the application be changed to support the new solar-powered motors. From listening to their plight, a behavior is derived.

Behavior: Someone can ask a solar-powered battery for its lumens required to operate and the motor will return an integer.

public int getLumensToOperate();
In an Abstract class
public abstract SolarPoweredMotor extends Motor{
abstract public int getLumensToOperate();
}
Both SolarPoweredMotor and BatteryPoweredMotor extend the abstract class Motor (see Figure 1).

Throughout your application, motors are treated the same in 90% of the code. When you're checking if you have a solar- or battery-powered motor, use instanceof.

if (instanceof SolarPoweredMotor){...} if (instanceof BatteryPoweredMotor){...}
You find out that horsepower is calculated for each type of motor so the getHorsepower() method is overloaded in each of the derived abstract classes. So far, this design looks good...

That is, until you find out that the sales department wants to sell a new type of motor that has both battery and solar power! The behaviors associated with solar- and battery-powered motors haven't changed. The only difference is you have a handful of motors that exhibit both behaviors.

The Problem with Modeling Behavior in an Abstract Class
Here's where the difference between an interface and an abstract class becomes apparent.

The goal is to add these motors with as little rework as possible. After all, code related to battery- and solar-powered motors is well tested and has no known bugs.

You can make a new abstract class that's SolarBatteryPowered but then your motor won't trigger your instanceof when you check for solar- and battery-powered motors. The other option is to make the new motor extend either the SolarPowered or BatteryPowered abstract class. But if you do that, the new motor will lose the functionality of the abstract class it didn't extend. Technically your new motor needs to extend both abstract classes, but you painted yourself into a corner that can be solved only with a lot of special-case coding.

The reason you're having problems is that by using abstract classes you implied not only a behavior hierarchy but a pattern of implementation as well! You modeled how the motors receive their behavior instead of just saying the motors have a specific behavior.

While the phrase "Someone can ask the motor for its horsepower rating, and the motor will return the rating as an integer" implies something about the behavior of an object, it doesn't deny any behavior. Nevertheless, when you modeled with abstract classes, you created an implementation pattern that later was found to be incorrect, even though the behavior in the hierarchy was accurate.

Modeling Behavior in an Interface
You can avoid accidentally implying an implementation pattern if you model behavior using interfaces. Let's review the behavior:

Behavior: Someone can ask the motor for its horsepower rating, and the motor will return its rating as an integer.

public interface Motor(){
public int getHorsepower();
}
Behavior: Somone can ask a battery-powered motor for its time to recharge and the motor will return its time as an integer.
public interface BatteryPoweredMotor extends Motor(){
public int getTimeToRecharge();
}
Behavior: Somone can ask a solar-powered motor for its lumens required to operate, and the motor will return its lumens as an integer.
public interface SolarPoweredMotor extends Motor{
abstract public int getLumensToOperate();
}
In this way, only behavior is modeled (see Figure 2).

Now, I'll describe the solar-battery-powered motor in question:

public DualMotor implements SolarPoweredMotor, BatteryPoweredMotor{
}
The dual-powered motor inherits behavior, not implementation (see Figure 3).

You can use abstract classes just as before, except in this case the abstract classes implement behaviors instead of defining them (see Figure 4).

Notice the two separate hierarchies. The interface defines behavior in a very pure way while the abstract class defines a pattern for implementation - including the origin of a given behavior. Notice how the bottom half of the diagram can be totally redesigned and yet the behavioral hierarchy remains intact. As long as the implementing class relies on the interfaces for behavior, the implementing class can change its parent abstract class without changing how other pieces of the code interact with it.

When to Use Abstract Classes
Now that I've fully discussed interfaces, abstract classes may seem like an evil half brother - something to be avoided. This is not the case! When you have a common implementation, abstract classes shine. Using abstract classes you can enforce an implementation hierarchy and avoid duplicate code. Using abstract classes, however, should not affect your decision to use interfaces to define your behavior.

Both parent and child abstract classes should implement interfaces that define the expected behavior if you think the implementation will change. In practice, relying on abstract classes to define behavior leads to an inheritance nightmare, while coding behavior with interfaces provides a cleaner separation of behavior and implementation. Thus it makes your code more resistant to change. If you want to modify your existing code to improve your design, I recommend reading Martin Fowler's book, Refactoring: Improving the Design of Existing Code (Addison-Wesley, 1999). He devotes an entire chapter to refactorings dealing with generalization.

More Stories By Anthony Meyer

Anthony Meyer is a
technical director and a Java developer at Flashline.com. His
experience includes the design, development and implementation of
large-scale, Java-based, Internet applications in the corporate Web
development environment. He has also created and implemented
corporate-focused reuse strategies in the
financial industry.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.