File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Abstract Classes and Methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Abstract Classes and Methods" Watch "Abstract Classes and Methods" New topic

Abstract Classes and Methods

Maureen Charlton
Ranch Hand

Joined: Oct 04, 2004
Posts: 218
I have just read some chapters on Abstract Classes and Methods - AND I know I have missed the point.

My question is why would you use abstract classes and methods?
What is the benefit of this?

Thanking you in advance.
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
They serve as a common base for a family of objects.
Say you are keeping track of ducks (quack) and have several species you want to differentiate between.
You could create an abstract class Duck with some common properties like weight and size, maybe speed) and abstract methods for species specific things (like nesting behaviour and sounds).
Your program would then (everywhere except when working with specific species like when inputting data) just use them as Duck objects and wouldn't have to care about what specific duck it's dealing with.

David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Another important distinction is that you cannot instantiate an abstract class; you must extend it with a subclass that implements all of the abstract methods. If it leaves any abstract method unimplemented, it must be declared abstract itself.

To use Jeroen's example, every duck you find in nature is actually a very specific species (subclass) of Duck. When two ducks mate and produce (instantiate) a new duck, their genes determine which species of Duck is created.

A common example from computing is an Transaction for an Account at a bank. The abstract Transaction class knows which Account it applies to and the monetary value of it. Using this base class you can determine the total number and value of Transactions executed against an Account. You can even call methods on it like execute() and undo().

Concrete (non-abstract) subclasses would be DepositTxn, WithdrawalTxn, TransferTxn, etc. When creating transactins, you use the subclasses. But when working with transactions in general, you refer to them using the abstract class.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
The Java API has many examples where abstract classes are useful. Of these, I would say that the Collections Framework gets the most use.

In fact, knowing how to use Collections is an important skill when programming Java. I suggest you go through the tutorial at the link given above. It will also help you see abstract classes in action.


Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: Abstract Classes and Methods
It's not a secret anymore!