Vous êtes sur la page 1sur 4

Java Q&A

Abstract classes vs. interfaces


When does it make sense to choose an abstract class over an interface?
By Tony Sintes

In Java, under what circumstances would you use abstract classes instead of interfaces?
When you declare a method as abstract, can other nonabstract methods access it? In
general, could you explain what abstract classes are and when you might use them?

Those are all excellent questions: the kind that everyone should ask as they begin to dig
deeper into the Java language and object-oriented programming in general.

Yes, other nonabstract methods can access a method that you declare as abstract.

But first, let's look at when to use normal class definitions and when to use
interfaces. Then I'll tackle abstract classes.

Class vs. interface


Some say you should define all classes in terms of interfaces, but I think recommendation
seems a bit extreme. I use interfaces when I see that something in my design will change
frequently.
For example, the Strategy pattern lets you swap new algorithms and processes into your
program without altering the objects that use them. A media player might know how to
play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback
algorithms into the player; that will make it difficult to add a new format like AVI.
Furthermore, your code will be littered with useless case statements. And to add insult to
injury, you will need to update those case statements each time you add a new algorithm.
All in all, this is not a very object-oriented way to program.

With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If
you do that, you can provide new media plug-ins at any time. Let's call the plug-in class
MediaStrategy. That object would have one method: playStream(Stream s). So to
add a new algorithm, we simply extend our algorithm class. Now, when the program
encounters the new media type, it simply delegates the playing of the stream to our media
strategy. Of course, you'll need some plumbing to properly instantiate the
algorithm strategies you will need.

This is an excellent place to use an interface. We've used the Strategy


pattern, which clearly indicates a place in the design that will change. Thus, you should
define the strategy as an interface. You should generally favor interfaces over inheritance
when you want an object to have a certain type; in this case, MediaStrategy. Relying on
inheritance for type identity is dangerous; it locks you into a particular inheritance
hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that
gives you a useful implementation or more type identity.

Interface vs. abstract class


Choosing interfaces and abstract classes is not an either/or proposition. If
you need to change your design, make it an interface. However, you may have abstract
classes that provide some default behavior. Abstract classes are excellent candidates
inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses
to provide others. For example, if you have an application framework, an abstract class
may provide default services such as event and message handling. Those services allow
your application to plug in to your application framework. However, there is some
application-specific functionality that only your application can perform. Such
functionality might include startup and shutdown tasks, which are often application-
dependent. So instead of trying to define that behavior itself, the abstract base class can
declare abstract shutdown and startup methods. The base class knows that it needs those
methods, but an abstract class lets your class admit that it doesn't know how to perform
those actions; it only knows that it must initiate the actions. When it is time to start up,
the abstract class can call the startup method. When the base class calls this method, Java
calls the method defined by the child class.

Many developers forget that a class that defines an abstract method can
call that method as well. Abstract classes are an excellent way to create planned
inheritance hierarchies. They're also a good choice for nonleaf classes in class
hierarchies. Neither can be instantiated. An interface has all public members and no
implementation. An abstract class is a class which may have the usual flavors of class
members (private, protected, etc.), but has some abstract methods.Use interface as much
as possible and only use an abstract class in the case where you want to provide some
(but not all, of course)
implementation. In practice, you want to prefer using, passing and returning interfaces,
not abstract class references. I think even in the case where you have an abstract class to
share some implementation, you still want to have an interface represent what will be
used by the client (for an example look at the new Collections -- you often pass around
Collection, List, Set or Map references, but not a AbstractList, AbstractSet or
AbstractMap, references).

1.Neither can not be initanitiated


2.Abstract class can have defined methods

If you have an abstract class with no defined methods, you're better off using an
Interface.
1]A class must have atleast one abstract method in order to make the class an abstract
class whereas in an interface all mathods are abstarct by default.

2]An abstarct mathod in the abstarct class can have a body whereas no mathod in an
interface can have a body.

3]All mathods in the interface must be implemented whereas it is not so with an


abstarct class.

4] Best way to understand both as take an example of mammel & man. Mammel is an
abstarct class where certain properties of a man are defined.(Like sound)This sound
mathod will not have a body but man class will implement it as man speaks. Dog class
will implement it as dog barks.

Interface whereas just another class that works as a contract between classes.You and
your wife live together and your wife does not know how to clean the house(don't mind
bare example) so you can't create another relationship as java does not accept multiple
relationship.So make a contarct with a maid she knows her job but you / your wife will
once tell how you want her to clean your house. Here the maid is an interface.
An abstract class can grow whereas an interface cannot. When you inherit from an
abstract class and later on if you want to add a new method or memeber variable then
you can do that and all existing derived classes and their uses ( if you have already used
derived classes in your code ) are still valid ( of course, you will have to provide some
default implementation of new methods ). But if you have created and used an interface
then you cannot add a new method to that interface without rewritng the existing code.

Comment from k.jones


02/09/2002
11:56AM PST
abstract classes --

Abstract classes are helpful when some of the behavior is defined for most or all
objects of a given type, but some behavior makes sense only for particular classes and not
a general superclass.

For example, suppose you want to create a benchmarking harness to provide an


infrastructure for writing benchmarked code. The class implementation could understand
how to drive and measure a benchmark, but it could not know in advance which
benchmark would be run. Most abstract classes fit a pattern in which a class's particular
area of expertrise requires someone else to provide a missing piece. Here is what such a
Benchmark class might look like.
abstract class Benchmark {
abstract void benchmark(); //no impl!
public long repeat (int count) {
long start = System.currentTimeMillis ();
for (int i = 0 i < count; i++)
benchmark();
return (System.currentTimeMillis () - start);
}
}
interfaces -- when to use

There are two important differences between interfaces and abstract classes.

1. Interfaces provide a form of multiple inheritance, because you can implement


multiple interfaces. A class can extend only one other class, even if that class has only
abstract methods.

2. An abstract class can have a partial implmentation, protected parts, static


methods, and so on, whereas interfaces are limited to public constants and methods with
no implementation.

These differences usually direct the choice of which is best to use in a particular
implementation. If multiple inheritance is important or even useful, interfaces are used.

Any major class you expect to be extended, whether abstract or not, should be
an implementation of an interface. Although this approach requires a little more work on
your part, it enables a
whole category of use that is otherwise precluded. For example, suppose we
had created an Attributed class instead of an Attributed interface with an AttributedImpl
implementation class.
Programmers who wanted to create new classes that extended other existing
classes could never use Attributed, since you can extend only one class. Because
Attributed is an interface,
programmers have a choice: they can extend Attributed Impl directly and avoid
forwarding, or, if they cannot extend, they can at least use forwarding to implement the
interface. You can even provide multiple possible implementations of the interface to
prospective users.

t boils down to this:


If you need "multiple inheritance" use an Interface
otherwise use an Abstract class.

You can change an abstract class by adding more methods and your existing
code will not break. But once you specify an Interface, it is cast in stone and cannot
change without breaking all your code that uses it. There have been places in the Java
libraries where the Sun team used an Interface and regretted it later

Vous aimerez peut-être aussi