Abstraction is used to hide the implementation details of a particular task(s) from a user. For example, Let’s say you get into your vehicle and start the engine there are a lot of different things that have to happen in order for your car’s engine to start. As the driver, you are not required to know what happens under the hood in order for you to be able to start your car. All the driver needs to know is if you turn the key the car will start. The details of how it start is hidden from the driver (abstracted).
In Java, we can achieve abstraction by using what is called an Abstract Class and or an Interface. Taking advantage of abstraction is where the majority of complexity will cease to exist in your applications. Also, code maintenance and maintainable will get much easier.
Understanding Abstract Classes
An abstract class is defined by the keyword abstract. Some facts regarding Abstract classes are as followed:
- An Abstract class can have 0 or more abstract methods.
- If a class declares at a minimum of 1 abstract method, then that class must be declared abstract.
- Abstract classes are not allowed to be instantiated.
Let’s take a look at a few examples regarding abstract classes below. Notice the keyword abstract when defining the class.
public abstract class MostBasicAbstractExample {
}
The example above is the most basic abstract class. Notice the keyword abstract.
public abstract class AbstractExampleWithMethods{
public void nonAbstractMethod()
{
}
public abstract void abstractMethod()
{
}
}
Notice I line 7 that we use the word ‘abstract’ to identify the method as an abstract method.