News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

Java Tutorial – 19 – Abstract

An abstract class provides a partial implementation that other classes can build upon. When a class is declared as abstract it means that the class can contain incomplete methods that must be implemented in subclasses, in addition to normal class members. These methods are left unimplemented and only specify their signatures, while their bodies are replaced by semicolons.

abstract class Shape
{
  public int x = 100, y = 100;
  public abstract int getArea();
}

Abstract class example

If a class called Rectangle inherits from the abstract class Shape, Rectangle is then forced to override the abstract getArea method. The only exception is if Rectangle is also declared abstract, in which case it does not have to implement any abstract methods.

class Rectangle extends Shape
{
  @Override public int getArea() { return x * y; }
}

An abstract class cannot be instantiated, but it can be used to hold instances of its subclasses.

Shape s = new Rectangle();

Even though an abstract class cannot be instantiated it may have constructors, which can be called from the subclass’s constructors by using the super keyword.

abstract class Shape
{
  public int x = 100, y = 100;
  public Shape(int a, int b) { x = a; y = b; }
}
 
class Rectangle extends Shape
{
  public Rectangle(int a, int b) { super(a,b); }
}

Abstract classes and interfaces

Abstract classes are similar to interfaces in many ways. They can both define method signatures that subclasses must implement, and neither one of them can be instantiated. The key differences are first that the abstract class can contain non-abstract members, while the interface cannot. And second, that a class can implement any number of interfaces but only inherit from one class, abstract or not. Note that an abstract class can, just as a non-abstract class, extend one superclass and implement any number of interfaces. An interface, however, cannot inherit from a class. Although it can extend another interface, which effectively combines the two interfaces into one.

Abstract class and interface guidelines

An interface is either used to define a specific functionality that a class can have, or to provide an interface for other programmers using a class. An abstract class on the other hand is used to provide a partial class implementation, leaving it up to subclasses to complete it. This is useful when subclasses have a lot of functionality in common, but also have some functionality that must be implemented differently for each subclass.

Recommended additional reading:
Sams - Teach Yourself Java in 24 Hours