mitchell bat wrote:Can anyone give me a simple and straight forward meaning and instances where you would use abstraction over interface and vice versa
I assume by "abstraction" you mean creating an
abstract class.
My take:
1. If you're not sure, favour
interfaces.
2. If you have something that you can provide a
general implementation for (whole or partial), write an
abstract class.
And you often see the two used together. For example: A
List in Java is a predictably ordered collection of items that can be directly accessed individually.
Sounds pretty “abstract” right? And yet it's the basis for practically every list (other than an array) that you use in Java. And the
List interface defines all the methods that a "list" is required to provide (and there are quite a few).
What does 'predictably ordered' mean? Well, basically it means that once an item is in a list, it must retain its position relative to others unless
(a) Another item is inserted before or after it.
(b) It's removed.
So if you go through a
List more than once, its items will be delivered in
the same order every time unless something is changed.
OK, so that's a
List. What about implementing it?
Well, one thing that a
List is required to do is return an
Iterator so, if you assume that someone else has told it how to return a specific item (see
List.get(int)), you can implement an Iterator that successively returns items numbered from 0 (the first item) to the last one in the list.
In fact,
AbstractList (←click), which is an
abstract class, does far more than that. It's an “almost complete” implementation of a
List that only requires you to add four methods -
get(),
set(),
size() and
remove() (and not always all of those) – to implement a concrete
List class based on any structure you like.
Pretty powerful, eh?
Winston