- most commonly to serve as a base-class or interface (some languages have a separate
interface
construct, some don't) - it doesn't know the implementation (that is to be provided by the subclasses / implementing classes)
- abstraction and re-use
- when the base-class can provide no meaningful default-implementation for a method (but allowing subclasses to re-use the non-abstract parts of the implementation; any fields, non-abstract methods, etc)
For example:
public abstract class Stream { /* lots of code, some abstract methods */ }
What the heck is a stream by itself? What kind of stream? a stream to a file? a network? a memory buffer? Each may have different and unrelated ways of reading / writing, but provide a common API. It makes no sense to create just a Stream
, but via the abstract
class, you can code to the Stream
API without knowing the details:
Stream s = CreateStream(...); // I don't *care* what kind of stream
s.Write(new byte[] {1,2,3,4,5});
s.Close();