http://www.developer.com/

Back to article

Designing with Interfaces & Abstract Classes


November 8, 2006

This series, The Object-Oriented Thought Process, is intended for someone just learning an object-oriented language and who wants to understand the basic concepts before jumping into the code, or someone who wants to understand the infrastructure behind an object-oriented language he or she is already using. These concepts are part of the foundation that any programmer will need to make the paradigm shift from procedural programming to object-oriented programming.

Click here to start at the beginning of the series.

In keeping with the code examples used in the previous articles, Java will be the language used to implement the concepts in code. One of the reasons that I like to use Java is because you can download the Java compiler for personal use at the Sun Microsystems web site http://java.sun.com/. You can download the standard edition, J2SE 5.0, at http://java.sun.com/j2se/1.5.0/download.jsp to compile and execute these applications. I often reference the Java J2SE 5.0 API documentation and I recommend that you explore the Java API further. Code listings are provided for all examples in this article as well as figures and output (when appropriate). See the first article in this series for detailed descriptions for compiling and running all the code examples.

In the previous column, you started your exploration of interfaces. In this installment, you delve deeper in interfaces and explain how they relate to abstract classes.

Implementing Contracts

Since the advent of computer software, the concept of reusing code has been reinvented many times. The Object-Oriented (O-O) paradigm is no different. One of the major advantages touted by O-O proponents is that you can write code once, and then reuse it to your heart's content.

This is true to a certain degree. As with all design approaches, the utility and the reusability of code depend on how well it was designed and implemented. Object-Oriented development does not hold the patent on code reuse. There is nothing stopping anyone from writing very robust and reusable code in a non-O-O language. Certainly, there are countless numbers of routines and functions, written in structured languages such as COBOL and C, which are of high quality and quite reusable.

Thus, it is clear that following the O-O paradigm is not the only way to take advantage of reuse. Yet, the O-O approach does provide several mechanisms for facilitating, and even enforcing, the development of reusable code. One way to accomplish this goal is to create something I refer to as programming contracts. In this article, you focus on using interfaces and abstract classes to create contracts and encourage reusable code.

What Is a Contract?

In the previous article, you learned about the concept of a design contract. In the context of this article, you will consider a contract to be any mechanism that requires a developer to comply with the specifications of an Application Programming Interface (API). Often, an API is referred to as a framework. The online dictionary Dictionary.com (www.dictionary.com) defines a contact as:

  1. An agreement between two or more parties for the doing or not doing of something specified.
  2. An agreement enforceable by law.

This is exactly what happens when a developer uses an API—with the project manager or business owner representing the law. In short, when using contracts, the developer is required to comply with the rules defined in the framework. This includes issues such as method names, number of parameters, and so forth. In short, standards are created to facilitate good coding practices.

The term contract is used widely in many aspects of business, including software development. Do not confuse the concept here with other possible software design concepts called contracts.

Enforcement is vital because it is always possible for a developer to break a contract. Without enforcement, a rogue developer could decide to re-invent the wheel and write his or her own code rather than use the code provided by the framework. There is little benefit to a standard if people routinely disregard or circumvent it. In Java and the .NET languages, the two ways to implement contracts are to use abstract classes and interfaces.

For this article, I used C# as the .NET representative. However, these concepts apply to all .NET languages, such as Visual Basic .NET.

Abstract Classes

One way a contract is implemented is via an abstract class. An abstract class is a class that contains one or more methods that do not have any implementation provided. Suppose that you have an abstract class called Shape. It is abstract because you cannot instantiate it. If you ask someone to draw a shape, the first thing they will most likely ask you is "What kind of shape?" Thus, the concept of a shape is abstract. However, if someone asks you to draw a circle, this does not pose quite the same problem because a circle is a concrete concept. You know what a circle looks like. You also know how to draw other shapes, such as rectangles.

How does this apply to a programming contract? Assume that you want to create an application to draw shapes. Your goal is to draw every kind of shape represented in your proposed design, as well as ones that may be added later. There are two conditions you must adhere to.

First, you want all shapes to use the same syntax to draw themselves. For example, you want every shape implemented in your system to contain a method called draw (). Thus, seasoned developers implicitly know that to draw a shape you simply invoke the draw () method, regardless of what the shape happens to be. Theoretically, this reduces the amount of time fumbling through manuals and cuts down on syntax errors.

Second, one of the most important Object-Oriented concepts is that every class must be responsible for its own actions. Thus, even though the class must provide a method called draw (), the class must provide its own implementation of the code. For example, a class called Circle and a class called Rectangle both have a draw () method; however, the Circle class obviously has code to draw a circle and, as expected, the Rectangle class has code to draw a rectangle. When you ultimately create classes called Circle and Rectangle, which are subclasses of Shape, these classes must implement their own version of Draw (see Figure 1).

Figure 1: An Abstract Class Hierarchy.

In this way, you have a Shape framework that is truly polymorphic. The Draw method can be invoked for every shape in the system, and invoking this method for each shape produces a different result. Invoking the Draw method on a Circle object draws a circle and invoking the Draw method on a Rectangle object draws a rectangle. In essence, sending a message to an object evokes a different response, depending on the object. This is the essence of polymorphism.

circle.draw();       // draws a circle
rectangle.draw();    // draws a rectangle

Look at some code to illustrate how Rectangle and Circle conform to the Shape contract. Listing 1 contains the code for the Shape class:

Listing 1

public abstract class Shape {
   public abstract void draw();
}

Note that the class does not provide any implementation for draw (); basically, there is no code and this is what makes the method abstract (providing code would make the method concrete). There are two reasons why there is no implementation. First, Shape does not know what to draw, so you could not implement the draw () method even if you wanted to. Second, we want the subclasses to provide the implementation.

Look at the Circle and Rectangle classes:

Listing 2

public class Circle extends Shape {
   public void draw() {System.out.println ("Draw a Circle");}
}
public class Rectangle extends Shape {
   public void draw() { System.out.println ("Draw a Rectangle");}
}

Note that both Circle and Rectangle extend (inherit from) Shape. Also notice that they provide the actual implementation (in this case, the implementation is pretty trivial). Here is where the contract comes in. If Circle inherits from Shape and fails to provide a draw () method, Circle won't even compile. Thus, Circle would fail in its attempt to satisfy the contract with Shape. A project manager can require that programmers creating shapes for the application must inherit from Shape. By doing this, all shapes in the application will have to provide a draw () method that complies with the Shape contract.

Note: If Circle does indeed fail to implement a draw () method, Circle will be considered abstract. Thus, yet another subclass must inherit from Circle and implement a draw () method. This subclass would then become the concrete implementation of both Shape and Circle.

Although the concept of abstract classes revolves around abstract methods, there is nothing stopping Shape from actually providing some implementation (the definition for an abstract class is that it contains one or more abstract methods. This implies that an abstract class can provide concrete methods as well). For example, although Circle and Rectangle implement the draw () method differently, they share the same mechanism for setting the color of a shape. So, the Shape class can have a color attribute and a method to set the color. This setColor () method is an actual concrete implementation and can be inherited by both Circle and Rectangle. The only methods that a subclass must implement are the ones that the superclass declares as abstract. These abstract methods are the contract.

Some languages, such as C++, use only abstract classes to implement contracts. Java and C#, however, have another mechanism, which implements a contract: an interface.

Interfaces

Before defining an interface, it is important to note that C++ does not have a construct called an interface. For C++, an abstract class provides the functionality of an interface. This raises an obvious question: If an abstract class can provide the same functionality as an interface, why do Java and C# bother to provide interfaces?

For one thing, C++ supports multiple inheritance whereas Java and C# do not. Although Java and C# classes can inherit from only one parent class, they can implement many interfaces. Using more than one abstract class constitutes multiple inheritance, thus Java and C# cannot go this route. Even though this explanation may specify the need for Java and C# interfaces, it does not really explain what an interface is. You need to explore what function an interface performs.

Note: Due to these considerations, interfaces are often thought to be a work-around for the lack of multiple inheritance. This is not technically true. Interfaces are a separate design technique, and although they can be used to design applications that could be done with multiple inheritance, they do not replace the concept of multiple inheritance.

As with abstract classes, interfaces are a powerful way to enforce contracts for a framework. Before you get into any conceptual definitions, it is helpful to see an actual interface UML diagram and the corresponding code. Consider an interface called Nameable, as shown in Figure 2.

Figure 2: A UML diagram of an interface.

Note that Nameable is identified in the UML diagram as an interface, which distinguishes it from a regular class (abstract or not). Also note that the interface contains two methods, getName () and setName (). Here is the corresponding code:

Listing 3

public interface Nameable {
   String getName();
   void setName (String aName);
}

In the code, notice that Nameable is not declared as a class, but as an interface. Because of this, both methods, getName () and setName (), are considered abstract and there is no implementation provided. An interface, unlike an abstract class, can provide NO implementation. As a result, any class that implements an interface must provide the implementation for all methods (in Java and C#, a class inherits from an abstract class whereas a class implements an interface).

Tying It All Together

If both abstract classes and interfaces provide abstract methods, what is the real difference between the two? As you saw before, an abstract class provides both abstract and concrete methods wheras an interface provides only abstract methods. Why is there such a difference?

Assume that you want to design a class that represents a dog, with the intent of adding more mammals later. The logical move would be to create an abstract class called Mammal:

Listing 4

public abstract class Mammal {
   public void generateHeat() {System.out.println("Generate heat");};
   public abstract void makeNoise();
}

This class has a concrete method called generateHeat () and an abstract method called makeNoise (). The method generateHeat () is concrete because all mammals generate heat. The method makeNoise () is abstract because each mammal will make noise differently.

Also, create a class called Head that you will use in a composition relationship:

Listing 5

public class Head {
   String size;
   public String getSize() {
      return size;
   }
   public void setSize(String aSize) {size = aSize;};
}

Head has two methods: getSize () and setSize (). Although composition might not shed much light on the difference between abstract classes and interfaces, using composition in this example does illustrate how composition relates to abstract classes and interfaces in the overall design of an object-oriented system. I feel that this is important because the example is more complete. Remember that there are two ways to build object relationships: the is-a relationship, represented by inheritance; and the has-a relationship, represented by composition. The question is: Where does the interface fit in?

To answer this question and tie everything together, create a class called Dog that is a subclass of Mammal, implements Nameable, and has a Head object (see Figure 3). The corresponding code is in Listing 6.

Figure 3: A UML diagram of the sample code.

In a nutshell, Java and C# build objects in three ways: inheritance, interfaces, and composition. Note the dashed line in Figure 3 that represents the interface. This example illustrates when you should use each of these constructs. When do you choose an abstract class? When do you choose an interface? When do you choose composition? Explore this idea further.

You should be familiar with the following concepts:

  • Dog is a Mammal, so the relationship is inheritance.
  • Dog implements Nameable, so the relationship is an interface.
  • Dog has a Head, so the relationship is composition.

Listing 6

public class Dog extends Mammal implements Nameable {
   String name;
   Head head;
   public void makeNoise(){System.out.println("Bark");};
   public void setName (String aName) {name = aName;};
   public String getName () {return (name);};
}

After looking at the UML diagram, you may come up with an obvious question: Even though the dashed line from Dog to Nameable represents an interface, isn't it still inheritance? At first glance, the answer is not simple. Although interfaces are a special type of inheritance, it is important to know what special means. Understanding these special differences is fundamental to a strong object-oriented design.

Although inheritance is a strict is-a relationship, an interface is not. For example:

  • A dog is a mammal.
  • A reptile is not a mammal.

Thus, a Reptile class could not inherit from the Mammal class. However, an interface transcends the various classes. For example:

  • A dog is nameable.
  • A lizard is nameable.

The key here is that classes in a strict inheritance relationship must be related. For example, in this design the Dog class is directly related to the Mammal class. A dog is a mammal. Dogs and lizards are not related at the mammal level because you can't say that a lizard is a mammal. However, interfaces can be used for classes that are not related. You can name a dog just as well as you can name a lizard. This is the key difference between using an abstract class and using an interface.

The abstract class represents some sort of implementation. In fact, you saw that Mammal provided a concrete method called generateHeat (). Even though you do not know what kind of mammal you have, you know that all mammals generate heat. However, an interface models only behavior. An interface never provides any type of implementation—only behavior. The interface specifies behavior that is the same across classes that conceivably have no connection. Not only are dogs nameable, but so are cars, planets, and so on.

The Compiler Proof

Can you prove or disprove that interfaces have a true is-a relationship? In the case of Java, you can let the compiler tell you. Consider the following code:

Dog D = new Dog();
Head H = D;

When this code is run through the compiler, the following error is produced:

Test.java:6: Incompatible type for Identifier.
Can't convert Dog to Head. Head H = D;

Obviously, a dog is not a head. However, as expected, the following code works just fine:

Dog D = new Dog();
Mammal M = D;

This is a true inheritance relationship, and it is not surprising that the compiler parses this code cleanly because a dog is a mammal.

Now, you can perform the true test of the interface. Is an interface an actual is-a relationship? The compiler thinks so:

Dog D = new Dog();
Nameable N = D;

This code works fine. So, you can safely say that a dog is a nameable entity. This is a simple but effective proof that both inheritance and interfaces constitute an is-a relationship.

Making a Contract

The simple rule for defining a contract is to provide an unimplemented method, via either an abstract class or an interface. Thus, when a subclass is designed with the intent of implementing the contract, it must provide the implementation for the unimplemented methods in the parent class or interface.

As stated earlier, one of the advantages of a contract is to standardize coding conventions. You can explore this concept in more detail by providing a good example of what happens when coding standards are not used. In this case, there are three classes: Planet, Car, and Dog. Each class implements code to name the entity. However, because they are all implemented separately, each class has different syntax to retrieve the name. Consider the following code for the Planet class:

Listing 7

public class Planet {
   String planetName;
   public void getplanetName() {return planetName;};
}

Likewise, the Car class may have code like this:

Listing 8

public class Car {
   String carName;
   public String getCarName() { return carName;};
}

And the Dog class may have code like this:

Listing 9

public class Dog {
   String dogName;
   public String getDogName() { return dogName;};
}

The obvious problem here is that anyone using these classes would have to look at the documentation (what a horrible thought) to figure out how to retrieve the name in each of these cases. Even though looking at the documentation is not the worst fate in the world, it would be nice if all the classes used in a project (or company) would use the same naming convention. It would make life a bit easier. This is where the Nameable interface comes in.

The idea would be to make a contract for any type of class that needs to use a name. As users of various classes move from one class to the other, they would not have to figure out the current syntax for naming an object. The Planet class, the Car class, and the Dog class would all have the same naming syntax.

To implement this lofty goal, you can create an interface (you can use the Nameable interface that you created previously). The convention is that all classes must implement Nameable. In this way, the users only have to remember a single interface for all classes when it comes to naming conventions:

Listing 10

public interface Nameable {
   public String getName();
   public void setName(String aName);
}

The new classes—Planet, Car, and Dog—should look like this:

Listing 11

public class Planet implements Nameable {
   String planetName;
   public String getName() {return planetName;};
   public void setName(String myName) {planetName = myName;};
}
public class Car implements Nameable {
   String carName;
   public String getName() {return carName;};
   public void setName(String myName) {carName = myName;};
}
public class Dog implements Nameable {
   String dogName;
   public String getName() {return dogName;};
   public void setName(String myName) {dogName = myName;};
}

In this way, you have a standard interface and you have used a contract to ensure that it is the case.

There is one little issue that you may have thought about. The idea of a contract is great as long as everyone plays by the rules, but what if some shady individual does not want to play by the rules (the rogue programmer)? The bottom line is that there is nothing to stop someone from breaking the standard contract; however, in some cases doing so will get them in deep trouble.

On one level, a project manager can insist that everyone use the contract just like team members must use the same variable naming conventions and configuration management system. If a team member fails to abide by the rules, he or she could be reprimanded or even removed from the team.

Enforcing rules is one way to ensure that contracts are followed, but there are instances in which breaking a contract will result in unusable code. Consider the Java interface Runnable. Java applets implement the Runnable interface because it requires that any class implementing Runnable must implement a run () method. This is important because the browser that calls the applet will call the run () method within Runnable. If the run () method does not exist, things will break.

Conclusion

Basically, contracts are "plug-in points" into your code. Any place where you want to make parts of a system abstract, you can use a contract. Instead of coupling to objects of specific classes, you can connect to any object that satisfies the contract. Abstract classes and interfaces provide the mechanism to implement these design techniques. By utilizing these object-oriented concepts, you can produce solid designs that are reliable, flexible, reusable, and very maintainable.

References

  • www.sun.com
  • Just Java 2, 6th Edition. Peter van der Linden. 2004, Sun Microsystems.

About the Author

Matt Weisfeld is a faculty member at Cuyahoga Community College (Tri-C) in Cleveland, Ohio. Matt is a member of the Information Technology department, teaching programming languages such as C++, Java, C#, and .NET as well as various Web technologies. Prior to joining Tri-C, Matt spent 20 years in the information technology industry gaining experience in software development, project management, business development, corporate training, and part-time teaching. Matt holds an MS in computer science and an MBA in project management. Besides The Object-Oriented Thought Process, which is now in its second edition, Matt has published two other computer books, and more than a dozen articles in magazines and journals such as Dr. Dobb's Journal, The C/C++ Users Journal, Software Development Magazine, Java Report, and the international journal Project Management. Matt has presented at conferences throughout the United States and Canada.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date