knowledge-kitchen

Object-Orientation - Abstract Classes (in Java)

Abstraction can provide stumbling blocks for people of strange intelligence.

Gustave Flaubert, in his unfinished satirical work, Bouvard et Pécuchet

  1. Overview
  2. Cannot Instantiate
  3. Pick Your Abstraction
  4. Mixing Abstractions
  5. Conclusions

Overview

Concept

An abstract class is a Java class that has been declared as abstract.

public abstract class Foo {

  /* some stuff here */

}

Similarity to concrete classes

Code-wise, an abstract class can encapsulate all the same properties and methods as a concrete class.

Difference from concrete classes

The only two differences between an abstract class and a concrete class are…

public abstract class Foo {

  pubic abstract int getRandom(int lowerBound, int upperBound);

}
Foo f = new Foo(); // a good view of a compilation error!

Legacy

Since abstract classes can contain abstract methods and because an abstract class cannot be instantiated…

public abstract class Foo {

  // an abstract method, for example
  pubic abstract int getRandom(int lowerBound, int upperBound);

}
public class Bar extends Foo {

  // this class *must* contain a concrete implementation of the abstract method
  public int getRandom(int lowerBound, int upperBound) {
    return rand = ( (int) Math.random() * (upperBound - lowerBound) ) + lowerBound;
  }

}

Frequently asked questions

There are three questions that commonly arise in relation to abstract classes:

  1. Why can you not instantiate an abstract class?

  2. When would you use an abstract class over an interface, and vice-versa?

Cannot Instantiate

Justification

An abstract class cannot be instantiated because any object made from it would potentially be missing the implementation of one or more methods.

public abstract class Foo {

  // an abstract method, for example
  pubic abstract int getRandom(int lowerBound, int upperBound);

}
Foo f = new Foo();
int num = f.getRandom(1, 10); // not allowed - this method has no concrete implementation!

Picking an Abstraction

Deciding between abstract classes and interfaces

Given both abstract classes and interfaces have the ability to encapsulate abstract methods, how do you pick between the two?

Deciding between abstract and concrete classes

Given that abstract classes can share all the same sorts of code as a concrete class, and more, how do you pick between the two?

Mixing Abstractions

Choices

When dealing with inheritance, polymorphism, interfaces, and abstract classes, we often study them in isolation. However, in reality, a single class might take advantage of all of these.

Imagine, for example, the following scenarios:

Conclusions

Abstract classes can be useful, when implemented with tact. You now have an understanding of the various ways in which this might be the case.