Java - Abstraction
Java - Abstraction
As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example,
when you consider the case of e-mail, complex details such as what happens as soon as you send
an e-mail, the protocol your e-mail server uses are hidden from the user. Therefore, to send an e-
mail you just need to type the content, mention the address of the receiver, and click send.
Java Abstraction
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 programming, abstraction is achieved using Abstract classes
and interfaces.
Java abstract classes may or may not contain abstract 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.
You can observe that except abstract methods the Employee class is same as normal class in Java.
The class is now abstract, but it still has three fields, seven methods, and one constructor.
Now you can try to instantiate the Employee class in the following way −
Open Compiler
/* File name : AbstractDemo.java */
public class AbstractDemo {
When you compile the above class, it gives you the following error −
Learn Java in-depth with real-world projects through our Java certification course. Enroll and
become a certified expert to boost your career.
Here, you cannot instantiate the Employee class, but you can instantiate the Salary Class, and using
this instance you can access all the three fields and seven methods of Employee class as shown
below.
Open Compiler
Output
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0
Note − Eventually, a descendant class has to implement the abstract method; otherwise, you would
have a hierarchy of abstract classes that cannot be instantiated.
Suppose Salary class inherits the Employee class, then it should implement the computePay()
method as shown below −
Output
Constructing an Employee
Computing salary pay for Mohd Mohtashim
salary: 69.23076923076923