| By Anthony Meyer | Article Rating: |
|
| April 1, 2001 12:00 AM EST | Reads: |
36,623 |
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{You make a handful of concrete implementations of this class, and version 1.0 of the application enters production.
abstract public int getHorsepower();
}
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{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.
abstract public int getTimeToRecharge();
}
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{Both SolarPoweredMotor and BatteryPoweredMotor extend the abstract class Motor (see Figure 1).
abstract public int getLumensToOperate();
}
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(){Behavior: Somone can ask a battery-powered motor for its time to recharge and the motor will return its time as an integer.
public int getHorsepower();
}
public interface BatteryPoweredMotor extends Motor(){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 int getTimeToRecharge();
}
public interface SolarPoweredMotor extends Motor{In this way, only behavior is modeled (see Figure 2).
abstract public int getLumensToOperate();
}
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.
Published April 1, 2001 Reads 36,623
Copyright © 2001 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
About 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.
- Performance of Java Compilers: An Empirical Study
- Java Kicks Ruby on Rails in the Butt
- Ulitzer’s Amazing First 30 Days in Public Beta
- 1st Annual Government IT Expo: Call for Papers Deadline July 15
- REA Is Where RIA Becomes the Norm
- Why an Application Grid?
- Will Ulitzer Dominate News Content on The Web? -Gartner
- Clear Toolkit 4: The Road Map
- Profiling Netbeans within Amazon EC2
- Java Persistence on the Grid: Approaches to Integration
- Performance of Java Compilers: An Empirical Study
- Java Kicks Ruby on Rails in the Butt
- Developing Rich Client Applications Using Swing - II
- The Right Time for Real Time Java
- Xpress Suite Adds Automatic Java to iPhone Conversion
- Ulitzer’s Amazing First 30 Days in Public Beta
- Initial Thoughts on IBM Acquisition of Sun Microsystems
- 1st Annual Government IT Expo: Call for Papers Deadline July 15
- Maximizing Java Performance with Bespoke Programming
- REA Is Where RIA Becomes the Norm
- A Cup of AJAX? Nay, Just Regular Java Please
- Java Developer's Journal Exclusive: 2006 "JDJ Editors' Choice" Awards
- The i-Technology Right Stuff
- JavaServer Faces (JSF) vs Struts
- Rich Internet Applications with Adobe Flex 2 and Java
- Java vs C++ "Shootout" Revisited
- Bean-Managed Persistence Using a Proxy List
- Reporting Made Easy with JasperReports and Hibernate
- What's New in Eclipse?
- Creating a Pet Store Application with JavaServer Faces, Spring, and Hibernate





































