Abstraction

Abstraction is one of the key concepts in object oriented programming.

The process of abstraction involves extracting what is key to design a class. For instance if we are designing a dog class, what is essential to a dog?

  1. four legs
  2. fur
  3. carnivorous

And what things does a dog do?

  1. runs
  2. barks
  3. bites

Based on these traits and behaviours we could write a general description, a class definition for a dog. Some dogs would not need all these things, and specific dogs might have extra qualities, but we can abstract a general dog class which we can base a description of a specific dog on. We have an abstraction of a dog.

Watch this video for another description

Abstraction in Java

We use abstraction in Java to define data types or classes which we can use to instatiate objects. To use an abstract data type there is no need to know anything about how the class is written, just what parameters are needed and what methods are available.

So for instance if I wanted to code a coin for a coin toss program I would first use abstraction to define what the key attributes and methods are for a coin.

Attributes

A coin has two sides called 'heads' and 'tails'. There are a lot of other things about co

ins such as their value and the image on them, but these are not general to coins or important to our program.

Methods

We will need to toss the coin. We will need to be able to read the result of the toss. So these will be our methods.

Now we can write an application programming interface (API) for our Coin class.

public class Coin
Coin (String id) create a coin named id
void toss() toss the coin
Boolean result() true for a head tossed

Once the code is written and tested for this class anyone could use it, based on this API, in their program without worrying about the specifics.

Coin dime = new Coin("dime");
dime.toss();
Boolean tossResult = dime.result();

So being able to use abstraction effectively is key to writing good OO code.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License