Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Abstract Classes and Methods

 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic