Incremental Java
Abstract Classes

abstract

We can declare classes as abstract, as in:
public abstract class Shape
{
   // Class definition goes here 
}
What does abstract mean? It means, we can't create (construct) objects of the abstract type.

Why would we do that?

The answer is inheritance. We declare a class that extends the abstract class. We can make the class concrete if we do two things:

So now, we need to explain abstract methods.

Abstract Methods

Abstract methods are methods without any implementation. They're basically the same as method signatures in interfaces.

An abstract class has zero or more abstract methods. This means an abstract class doesn't need any abstract methods, although usually it has one.

Here's an example:

public abstract class Shape
{
   public abstract int getPerimeter() ;
   public abstract int getArea() ;
}
When you declare abstract classes, you want someone to write a child class that makes it a concrete class. To make a concrete class, you extend the abstract class and implement all abstract methods.

Does that sound a lot like interfaces? There are some differences.

Differences Between Abstract Classes and Interfaces

Abstract classes can have non-abstract methods that have method definitions. This gets inherited. Interfaces do not allow any method definitions.

Abstract classes can have constructors. This may seem a little silly because you can't construct objects from an abstract class. However, when you write child classes, it calls the constructor of the parent class, even if the parent class is abstract.

Interfaces can't have constructors.

Abstract classes can have private methods. Interfaces can't.

Abstract classes can have instance variables (these are inherited by child classes). Interfaces can't.

Finally, a concrete class can only extend one class (abstract or otherwise). However, a concrete class can implement many interfaces. This fact has nothing to do with abstract classes. A class can only have one parent class (although the parent class can have a parent class, and its parent can have a parent class, and so forth), regardless of whether the class is abstract or not.

In general, the programming community leans to using interfaces over abstract classes, although both serve similar roles.