Wednesday, June 11, 2008

Dev : What is an abstract class

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.

Let's look at the following example: Each animal sure has some common actions can be defined in abstract class, but we implement uncommon actions to be implemented in sub class.

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();
}

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!"); }
}

Now you may be wondering why not declare an abstract class as an interface, and have the Dog and Cow implement the interface. Sure you could - but you'd also need to implement the eat and sleep methods. By using abstract classes, you can inherit the implementation of other (non-abstract) methods. You can't do that with interfaces - an interface cannot provide any method implementations.

No comments: