Imagine you are driving a car.
While driving you accelerate, apply breaks, shift gears, right?
Do you ever think about the car engine which produces the energy to move the vehicle ahead?
No
You just focus on the things which are important while driving. Knowing how engine works won’t help you.
You remember the important stuff and forget about the background details.
This is what exactly abstraction is about.
Abstraction is a process of hiding by which we hide the implementation details from the user and providing only the functionality.
In simple words, abstraction is a process of focusing on essential details and hiding background details.
This way, the user will know the answer to what but not the how of it.
This can also be viewed as data hiding or only showing the essential details.
This becomes necessary as not every user has to see or know everything.
For eg, a person who is using a software does not need to view the admin panel. That’s of no use to him.
Also, security is at risk if there is no abstraction.
Implementing abstraction
In Java, abstraction can be achieved using interfaces and abstract classes.
An abstract class is an incomplete class, to use it we need to extend it.
Extending the abstract class makes it complete.
An abstract class is declared by using the abstract keyword.
An abstract class may or may not contain abstract methods.
A method without body is known as abstact method.
It is only declared in an abstract class and defined in the class which extends the abstract class.
A class with any number of abstract methods must be declared as an abstract class.
public abstract class ClassName{
//Members
}
There are no differences while writing a class and an abstract class, the only addition is the abstract keyword.
We can extend this abstract class the same way we extend normal classes.
public class AnyClass extends ClassName{
//Members
}
Just like that.
An abstract method is a special method with only declaration part . the special thing about abstact method is that No Body/Definition in the declaration class.
The definition of the method is contained by the child class extending the class containing the abstract method.
To declare an abstract method, the keyword abstract is used.
public abstract returnType methodName();
The implementation of the method can be done in any class which extends the abstract class containing this method.
We can achieve complete abstraction using interfaces.
To summarize
- Abstraction is a process of hiding background details and focusing on the essential details.
- In Java, abstraction can be achieved using interfaces and abstract classes.
- While writing an abstract class or an abstract method the keyword abstract is used.
- An abstract method is a method without a body.
- It is only declared in an abstract class and defined in the class which extends the abstract class.