Java - Abstraction - 093858
Java - Abstraction - 093858
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.
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.
This section provides you an example of the Java Abstract Class. To create an abstract
class in Java, just use the abstract keyword before the class keyword, in the class
declaration.
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
Page 3 of 11
one constructor.
Now you can try to instantiate the Employee class in the following way −
Open Compiler
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
You have to place the abstract keyword before the method name in the method
declaration.
Instead of curly braces, an abstract method will have a semoi colon (;) at the
end.
Any class inheriting the current class must either override the abstract method or
declare itself as abstract.
Suppose Salary class inherits the Employee class, then it should implement the
computePay() method as shown below −
Page 9 of 11
Open Compiler
return name;
}
Output
Page 11 of 11
Constructing an Employee
Computing salary pay for Mohd Mohtashim
salary: 69.23076923076923