Summary

A recap of abstraction as an OOP idea and the `abstract` class as the Java tool that helps you reach it.

Journeyman · Java · OOP · Updated

By

Abstraction is the process of simplifying how an object is used by exposing only the necessary information. One way to achieve abstraction is by creating an inheritance structure. Parent classes are more generic, and child classes are more specific. The more generic a class is, the more abstract it is as well.

Because parent classes are more abstract than their inherited child classes, we may not want our code to allow the instantiation of some parent classes. Java uses the abstract keyword to mark a class to ensure that it must be extended. In other words, you cannot create an instance of that class.

Therefore, Abstraction is an OOP concept, while an abstract class is a Java construct. Abstraction is a goal we strive to achieve when building software that is easy to maintain. An abstract class is a tool that we can use to help us achieve this goal.

Do it: make Shape abstract

A drawing app works out how much paint each shape needs from its area. Right now Shape is an ordinary class whose area() returns 0, and Rectangle and Triangle forgot to override it. So every shape says it needs no paint.

Every kind of shape works out its area in its own way, and a shape of no kind has no area at all. So Shape is a good candidate for an abstract class: then nobody can create a plain Shape, and Java makes every kind of shape write its own area().

The two kinds of shape each get two values when they're created:

  • Rectangle(double width, double height): its area is width × height.
  • Triangle(double baseWidth, double height): its area is half of base × height.

For example, a 4 by 3 rectangle and a triangle with a base of 4 and a height of 3:

Shape Area
new Rectangle(4, 3) 4 × 3 = 12.0
new Triangle(4, 3) 4 × 3 ÷ 2 = 6.0

So new Rectangle(4, 3).area() returns 12.0.

Your job: change Shape and finish the two kinds of shape.

  • Make Shape an abstract class.
  • Make area() an abstract method that returns a double, with no body.
  • In Rectangle, override area() to return width * height.
  • In Triangle, override area() to return baseWidth * height / 2.

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets