abstract keyword in Java

The "abstract" keyword can be used on classes and methods.
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
abstract class AbstractDemo{
  // declare fields
   // declare non-abstract methods
   // declare abstract methods
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like
abstract void abstractMethodName();

Abstract classes and abstract methods are like skeletons. It defines a structure, without any implementation.
Note that, only abstract classes can have abstract methods. Abstract class does not necessarily require its methods to be all abstract.
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.

Let's look at below example in Java API
The "java.io.OutputStream" is a abstract class. Its subclasses includes:
ByteArrayOutputStream, FileOutputStream, FilterOutputStream, ObjectOutputStream, OutputStream, PipedOutputStream

All these subclass inherit and implement "java.io.OutputStream"'s abstract methods:
write(byte[] b)
write(byte[] b, int off, int len)
write(int b)

It does not make sense to give them a implementation in “java.io.OutputStream”, because each is really specific to the type.

For example, the implementation for ByteArrayOutputStream.write() is necessarily different for FileOutputStream.write().
Abstract class is a parent for a collection of subclasses, where itself declares certain methods but doesn't define any implementations. This is so that, subclasses all inherit the same set of methods and variables, and are free to implement them or add in addition.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...