aspose file tools*
The moose likes Java in General and the fly likes Interface and Abstract Classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Interface and Abstract Classes" Watch "Interface and Abstract Classes" New topic
Author

Interface and Abstract Classes

gautham kasinath
Ranch Hand

Joined: Dec 01, 2000
Posts: 583
HI!
Well I ve been coding in Java for a long time now but I ve a basic doubt..
Please explain the practical use of Interfaces and that of Abstract classes.
An abstract class doesnt define the methods but then why do I need a class that doesnot define the methods.. is it another way for multiple inheritance??
Please explain.
Regds
Gautham kasinath


"In the country of the blind, the one eyed man is the King"
Gautham Kasinath CV at : http://www.geocities.com/gkasinath
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
There's a sort of idiom which I use in many projects which I hope illuminates this a bit. First I'll describe what I do, then I'll try and describe why it is useful.
If I have a concept in a system, rather than just writing a class for it, I'll typically write an interface instead. The interface just contains the methods which comprise the behaviour of the concept. It says nothing about how any internal state is represented, what other classes it needs to keep references to or whatever.
Whenever another class needs to use this concept, I always make the method parameters, return values and member variables use the interface type. Code which uses this may use any of the methods on the interface, but know nothing about the actual implementation of the class.
To actually implement the interface, I occasionally just declare a class which implements it, and fill in all the code for the methods. More often though, I first define an abstract class which implements the interface and provides absolute-minimum implementations for all the methods. Then I write one or more real implementations which inherit from that abstract class.
Here is an example from one of my projects:

Now as to why this is useful.
Notice that code which uses these classes creates objects of specific classes (new DollarAmount(...)), but stores and passes only the interfaces. This means we can write a method such as getSalesTax() which works with whichever currency is being used.
Creating the abstract class allows the creation of concrete classes to be as simple as possible, instead of requiring each implementation to redefine all the methods in teh interface, only the ones it really needs to implement are coded, and the rest are left to the abstract parent class to handle.
All of this makes for much simpler maintenance and addition later. In particular it helps to remove "circular references" where two classes refer to each other, so neither one can be compiled first.
For an exmaple of this idiom in the system APIs, look at any of the ..Listener / ..Adapter pairs used for event handling in AWT and Swing.

Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
According to the book "Design Patterns":
There are two benefits to manipulating objects soley in terms of the interface defined by abstract classes:


1) Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that the clients expect


2) Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class(es) defining the interface.


This so greatly reduces implementation dependencies between subsystems that it leads to the following principle of reusable object-oriented design:


Program to an interface and not an implementation

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Frank there is something wrong with your example. The interface "Amount" has two non-abstract methods. This is not permitted in an interface.
Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241
...not to mention that static (as a method modifier) is also a no-no in interfaces....
Art
[This message has been edited by Art Metzer (edited April 06, 2001).]
gautham kasinath
Ranch Hand

Joined: Dec 01, 2000
Posts: 583
Hi!
Well that really was a great expl. for an Interface and Abstract class.. I ve gone thru it 11 times already but I am not able to comprehend the same fully..
Anyone please give me a simpler and practical explaination..
Regds
Gautham Kasinath
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
OK let's try Cars.
Say that I happen to work for the automotive industry and we are just getting into the Java coding business. However I want to leverage my code across lots of applications in the Division.
I know that we are eventually going to do LOTS of stuff with Car objects, and I want to make sure that we all work in unison.
So I make an interface called Car and in that interface I define all of the things that I want to make SURE that every thing that implements Car takes care of. So I put empty methods for Steering(), and Stopping() and WipeWindsheilds() and OpenDoor() etc. Every one in the department knows the methods that Car must do.
Now I make
abstract Class Sedan implements Car{ }
abstract Class TwoDoor implements Car{ } etc.
We all know that these two classes have identical methods from Car and we know how to use them. They must have those methods but maybe not ALL their methods are implemented. Even if they were, you can not really build a Sedan, you have to build a specific model of a Sedan (like a Buick). So I made the class abstract to prevent someone trying to make an instance of it. Eventually when the Buick class is created it will inherit all of the implemented methods that Car insisted on and all of the implemented methods that Sedan added, and Buick may have to add it's own implementation for any abstract methods that I may have left in Sedan. So extending the abstract is a bit easier in that I don't HAVE to implement every one of those pesky methods, however it adds the danger of typoing. With an interface you have to implement each and every method (and SPELL it correctly or the compiler complains). When sub-classing if you try to override a method and mis-spell it, it just becomes an additional method and the original method is still there and active - no compiler to give you a clue.
Anyway - back to interfaces:
I can now make "generic variables".
TwoDoor t = new TwoDoor();
Buick b = new Buick();
Car c1 = b;
c1 = t;
The c1 variable can hold any class that implements Car.


"JavaRanch, where the deer and the Certified play" - David O'Meara
Ashwin Desai
Ranch Hand

Joined: Jul 17, 2000
Posts: 124
Hi,
Abstract classes should be used in the following cases:
1) State :
If there is state to be maintained in the class hierarchy.

2) Default implementations:
If default implementations are to be provided for some methods, not necessarily all.

Interfaces :
Interfaces are used to specify only the BEHAVIOR for a particular class hierarchy. No state is maintained and no default implementations are provided.
Thus, when a class implements an interface, it agrees to support a fixed set of behaviour(s) (that is published publicly).
for e.g.
an ActionListener interface has a method actionPerformed(ActionEvent e).

In the above piece of code the class MyActionListener implements ActionListener. The Java Runtime knows only about the published interface (i.e. ActionListener ) of the class and thus only about the actionPerformed() method.
You may subsitute another class for the above, but as long as it agrees to the ActionListener contract (i.e. provides an actionPerformed() method), there would be no problems.
Hope this helps.
Ashwin.
[This message has been edited by Ashwin Desai (edited April 11, 2001).]
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
TwoDoor t = new TwoDoor();
Buick b = new Buick();
Car c1 = b;
c1 = t;
The c1 variable can hold any class that implements Car.

TwoDoor is an abstract class so the first instruction would not be permitted.
You could do:
Sedan s = new Buick();
or
Car c = new Buick();
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Yeah, your right - quick think of a TwoDoor Car . . .
Class Corvette extends TwoDoor{ }
Car cool = new Corvette();
Jeffrey Ang
Greenhorn

Joined: Mar 26, 2001
Posts: 6
Abstract classes are used if you don't want an instance of that class to be created. Some or all of its methods could already have an implementation. That means an abstract class can have no abstract method. On the other hand, if your abstract class contains only abstract methods then consider redesigning your class. Maybe an interface would have been more suitable. Also, take note that all methods of an interface are implicitly public so you cannot override it with a more restrictive access modifier.
Laojar Chuger
Ranch Hand

Joined: Dec 20, 2000
Posts: 111
Interface is a higher level of abstraction over class. The relationship is that class is an instance of interface, whereas object is an instance of class. Abstract class actually bridge the gap between the interface and class. If no field is declared, an abstract class is almost the same as interface except no other class can be extended. On the other hand, an abstract class can have only one abstract method, which is, in most cases, just a very narrow abstraction over the class. IMHO, interface is really a better tool for a general abstraction. Since Java puts no limitation on the how many interfaces a class can implement, interface is much better than abstract class for the dynamic binding, which is real advantage of Java and other OO languages.
Rahul Mahindrakar
Ranch Hand

Joined: Jul 28, 2000
Posts: 1859
The most practical use of interfaces/Abstract classes in my opnion is the Java Collections. If you devote time to study the collections API from the designers point of view one learns a lot.
Laojar Chuger
Ranch Hand

Joined: Dec 20, 2000
Posts: 111
Exactly! I guess that's why collection interface comes out. The release of Java collection makes it possible to manupulate almost all the data structure with one set of interfaces.
Fred Hosch
Author
Greenhorn

Joined: Apr 16, 2001
Posts: 23
"program to an interface" is a well-known and useful hueristic.
the point, of course, is to reduce dependencies. an interface
defines minimal functionality that a client requires of a server.
the client does not care what kind of object, from what kind of
hierarchy, shows up to provide the service. the client is as
independent of the server and its implementation as possible.
so i use an interface unless i have a good reason not to.
if i want to provide some "default" state or "default"
implementation, then i use an abstract class. then i'm
defining the root class of an implementation hierarchy.
and the abstract class often implements an interface that
specifies the basic functionality of the hierarchy.
gee, did that add anything to the discussion ;-?

------------------
Fred Hosch
Author of:
An Introduction to Software Construction with Java


Fred Hosch<br />Author of:<br /><a href="http://www.amazon.com/exec/obidos/ASIN/0471354899/ref=ase_electricporkchop/107-7882751-0234939" target="_blank" rel="nofollow">An Introduction to Software Construction with Java</a>
Jaime Nino
Author
Greenhorn

Joined: Apr 16, 2001
Posts: 4
Abstract classes provide generalization at the level of an implementation hierarchy, whereas the abstract class is the
root of a tree of subclass implementations. Thus all the classes
in that hierarchy share implementation knowledge. The abstract
class models a generalized version of that hierarchy, which can be gotten via factorization of data, functional specification as well as functional implementation. Although we
call it an abstract class, in principle it sets up an implementation hierarchy with its own set of common implementation characteristics, ie, its own implementation flavor.
An interface provides only functional specification without any presupposed knowledge on any implementation flavor. There can be many different class hierarchies implementing one given interface. The payoff of interfaces and abstract classes comes in polymorphism. With a variable reference to an abstract class A we can provide it with instances from any of the different concrete subclasses implementing A, all these subclasses coming from the same hierarchy. With a variable reference to an interface I, we
can provide it with instances from any concrete subclasses from any class hierarchy implementing I. Thus the use of interfaces
coupled with the use of variable references to interfaces allow you to set up your code for more adaptability to changes, (flexibility).
One common saying in the software pattern community states: Program to an interface not to an implementation. This saying is put into practice in Java by using references to abstract classes or even better to interfaces for both component variables in classes and parameters in methods.
In programming both abstract classes and interfaces have their use and place. Interfaces provide generalization across different class hierarchies. Abstract classes provide commonality of an implementation hierarchy. And both are the best ways to set up your code for polymorphism.

------------------
Jaime Nino
Author of:
An Introduction to Software Construction with Java


Jaime Nino<br />Author of:<br /><a href="http://www.amazon.com/exec/obidos/ASIN/0471354899/ref=ase_electricporkchop/107-7882751-0234939" target="_blank" rel="nofollow">An Introduction to Software Construction with Java</a>
Amit Badle
Ranch Hand

Joined: Jan 31, 2001
Posts: 41
Hi all,
From what I read in this post and especially cindy�s explanation the importance of interfaces and abstract classes is clearly seen. And also Rahul has shown us the practical use of interfaces. But my question is that instead of implementing all the methods of an interface why cant v have interfaces wer v cud implement only the methods v want to? Wud it lead to a catastrophe in program design or add to its flexibility?
in short an abstract class but w/o the overhead.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
OK let's say we have this:

The idea of the interface is that if you have an object of type AnInterface, you automatically know that it must implement method1, method2, and method3. If AClass doesn't have to do that, how would I know which methods were safe to run on an object ot type AnInterface?
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

There is a cheat method for you, if you *really* want to avoid writing blank bodies for all the methods you define in an interface. Imagine if you implemented an interface containing 10 methods, but only required your class to respond/use 1 of those.

Enter the Adapter Classes!

Check out WindowAdapter or MouseAdapter in the Java API. (they're in java.awt.event) They are nothing more than classes that implement the respective Listener interfaces and provide a default (blank) implementation for that interface. These adapter classes are used all the time as short-hand when doing event handling, especially in anonymous inner classes.

The danger of using these classes, as Cindy has already mentioned, is that you lose the compile-time checks that make interfaces so useful.
wei Qiao
Greenhorn

Joined: Jun 19, 2000
Posts: 23
many people had said enough for the difference between interface and abstract classes. I have one more thought about when I will choose one or another.
I use interface when I need to define a common behavior amond different categories of obejects or I don't care what object it will be. So each object can still have their oen super class and enjoy th multiple inheritence.
I use abstract class to define interfaces for a class of objects to extends from for similiar nature.

Hope it helps

Wei Qiao
Anil Vupputuri
Ranch Hand

Joined: Oct 31, 2000
Posts: 527
Can u explain more clearly. Ru again going to inheritance using abstract class.

SCJP 1.5, SCEA, ICED (287,484,486)
 
Don't get me started about those stupid light bulbs.
 
subject: Interface and Abstract Classes