Java Abstraction:
- Abstraction is the process of hiding the execution details and showing the functionality to the user only.
- Abstraction lets you pay attention to how the object is doing instead of how it is done.
Real Life Example of Abstraction:
- We only know about running a car, but it does not know how it works, and we do not even know the internal functionality of the car.
There are two ways to get an abstraction in Java:
- Abstract class (0 to 100% abstraction)
- Interface (100% abstraction is received)
Abstract class / method:
- An abstract class is a class that has been declared with the keyword abstract.
- It can be mixed with implementation or without declared methods.
- It needs to be expanded and all abstract methods should be implemented in the child class.
- It can not be interpreted to mean that you can not make an object of an abstract class.
- Abstract method is a method which has been declared without implementation.
Syntax:
1 | abstract class A{} |
Example of Abstract class & Method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | abstract class Vehical { abstract void run(); void display() { System.out.println("Display Method"); } } class BMW extends Vehical { public void run() { System.out.println("Run method"); } public static void main(String args[]) { BMW obj = new BMW(); obj.run(); } } |
Interface:
- An interface in Java is a template of a class.
- This collection of abstract methods means that all methods are abstract methods in the interface.
- With abstract methods, an interface can also contain constants, default methods, static methods, and nested types.
- The interface in Java is a mechanism to achieve completely abstraction.
- It can not be started like an abstract class.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | interface Demo { static void display(); static void run(); } class TestClass implements Demo { public void display() { System.out.println("Dispaly Method"); } public void run() { System.out.println("Run Method"); } public static void main(String args[]) { TestClass obj = new TestClass(); obj.display(); } } |
When do you use java abstraction?
- When you know that there must be something, but it is not certain how it should look.
Benefits of java Abstraction:
- By using abstraction, we can separate things that can be grouped in some other way.