What is an abstract class ?

Posted By: Matpal Media - 6:04 AM
An abstract class, or abstract base class (ABC), is a class that cannot be instantiated. Such a class is only meaningful if the language supports inheritance. An abstract class is designed only as a parent class from which child classes may be derived. Abstract classes are often used to represent abstract concepts or entities.
The incomplete features of the abstract class are then shared by a group of subclasses which add different variations of the missing pieces.

Abstract class contains one or more abstract methods (methods without implementation).
An abstract method is a method that is declared, but doesn't contain implementation (like method declaration in the interface).

Suppose we were modeling the behavior of animals, by creating a class hierarchy that started with a base class called Animal. Animals are capable of doing different things like flying, digging and walking, but there are some common operations as well like eating and sleeping. Some common operations are performed by all animals, but in a different way as well. When an operation is performed in a different way, it is a good candidate for an abstract method (forcing subclasses to provide a custom implementation). Let's look at a very primitive Animal base class, which defines an abstract method for making a sound (such as a dog barking, a cow mooing, or a pig oinking).


public abstract Animal
{
   public void eat(Food food)
   {
        // do something with food.... 
   }

   public void sleep(int hours)
   {
        try
    {
        // 1000 milliseconds * 60 seconds * 60 minutes * hours
        Thread.sleep ( 1000 * 60 * 60 * hours);
    }
    catch (InterruptedException ie) { /* ignore */ } 
   }

   public abstract void makeNoise();
}

Note that the abstract keyword is used to denote both an abstract method, and an abstract class. Now, any animal that wants to be instantiated (like a dog or cow) must implement the makeNoise method - otherwise it is impossible to create an instance of that class. Let's look at a Dog and Cow subclass that extends the Animal class.


public Dog extends Animal
{
   public void makeNoise() { System.out.println ("Bark! Bark!"); }
}

public Cow extends Animal
{
   public void makeNoise() { System.out.println ("Moo! Moo!"); }
}

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.