OOP Abstraction Introduction#
What Is The Abstraction In OOP?#
Abstraction
is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.- In Java,
abstraction
is achieved using Abstract classes and interfaces.
Abstract Class#
- A class which contains the
abstract
keyword in its declaration is known as abstract class.Abstract classes
may or may not containabstract methods
, i.e., methods without body ( public void get(); )- But, if a class has at least one
abstract method
, then the class must be declared abstract. - If a class is declared abstract, it cannot be instantiated.
- To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it.
- If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
Abstraction Example#
- To create an abstract class, just use the
abstract
keyword before the class keyword, in the class declaration. Then to createabstract
methods, you also put theabstract
keyword after the access modifier of methods and these methods must not have body.
Employee.java | |
---|---|
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
|
- We can inherit the properties of
Employee abstract class
just like concrete class in the following way.
Employee.java | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Employee abstract class
we have two abstract methods
so we have to @Override
them in Developer
child class for providing implementations.
- Here, for testing, you cannot instantiate the
Employee
class, but you can instantiate theDeveloper
Class, and using this instance you can access all the fields and methods ofEmployee
class as shown below.
JavaAbstractionMain.java | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 |
|