Core JAVAWrite Once, Run Anywhere |
Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class.
If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclassed. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own.
Abstract Class:
Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword.
Notice that nothing is different in this Employee class. The class is now abstract, but it still has three fields, seven methods, and one constructor. Now if you would try as follows:
Example:
Output:
Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract. The abstract keyword is also used to declare a method as abstract.
An abstract methods consist of a method signature, but no method body. Abstract method would have no definition, and its signature is followed by a semicolon, not curly braces as follows:
Declaring a method as abstract has two results:
A child class that inherits an abstract method must override it. If they do not, they must be abstract,and any of their children must override it.
Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated. If Salary is extending Employee class then it is required to implement computePay() method as follows: