Abstraction is very important in Java. And there’s the keyword abstract. But the use of abstract is not abstraction. It’s a common misconception that the abstract keyword is used for abstraction.
I found this on some crappy collection of “interview questions”:
Abstraction refers to the ability to make a class abstract in OOP.
Set— a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets.
So in Java interfaces are used for abstraction within the design of an application. An interface can be used to model some abstract idea.
Java code runs on a virtual machine – the JVM. That JVM is an abstraction of a machine. It works the same on Linux, Mac and Windows. So here we can use this abstraction to write apps that run on different systems.
Then there are classes in Java such as
HashSet that implement some abstract data type. The type
EnumSet is abstract because it is not a full implementation. But it isn’t as abstract as a
Set because it uses enums. That’s a technical detail. But it’s not concrete enough because that base class doesn’t actually define how the data is stored (it’s always a bit vector, but
RegularEnumSet is limited to 64 elements).
Abstraction is very important when you design your application. When you describe the high-level architecture you don’t want to tie yourself down to some implementation. Technicalities and specific details do not matter yet. You can still decide that later. And when your architecture is based on abstract ideas you can replace any implementation with another at any time.
You can switch from Mac to Linux at any time. You can switch from 32-bit to 64-bit without even recompiling. You can replace a
LinkedList with an
Abstract Classes vs. Interfaces
A class is abstract when it builds the base of some other classes and can not be initialized. This is a static approach to reduce code redundancy by reusing it in childclasses. Such an abstract class can have abstract methods. But it also contains some methods that are implemented.
To define some abilities and to model some abstraction you do not use an abstract class. That’s what interfaces are for. They can contain some default methods, but not any state. And default methods should only apply very simple things using other methods. That could be delegation or iteration. An abstract class on the other hand would implement some basic behaviours. That’s some concrete implementation of the abstract idea.
When to use Interfaces
Use interfaces for abstract ideas so you can have multiple implementations. Then you can also use it as the type of your variables, so you can switch the actual type without altering your code.
When to use abstract Classes
Use abstract classes if you have multiple implementations that have some implementations in common. Put that in an abstract class. But that is fixed and can’t be changed at runtime. Use composition over inheritance if you need more flexibility.