Preface – This post is part of the Object Oriented ABAP series.
Table of Contents
Introduction
In simpler words, a class can be called as an abstract class, if it would contain at least one abstract method. Now, the question comes, what is an abstract method? An abstract method is a method which does not have an implementation. Now, a question will come to your mind, if a method is not having any implementation, then what is the use of this abstract method or class.
So, the answer to your question is: We can implement that abstract method, but not like any other simple class. There is a particular way to implement it.
To implement an abstract method, a subclass of an abstract class is required. There is no need to instantiate an object of an abstract class. Instantiation is possible only for the subclass. An abstract class can have non-abstract methods as well and It is not necessary to redefine non-abstract methods in each and every inherited class.
Following points, we need to remember while creating an abstract method:
- Abstract methods can never be private.
- Only instance methods are allowed to be an abstract method.
Definition:
Class with at least one abstract method (which does have implementation) is known as ‘Abstract class’.
Example: Let’s take a simple real time scenario, where ‘TELEPHONE’ is your class. This class is having four Methods (each method depicts one functionality):
- PICKUP_CALL
- DROP_CALL
- REJECT_CALL
- DIAL_NUMBER
For the first three methods, the functionality would be the same (meaning, you just need to click on one button). But in the fourth method, there could be many possibilities of dialing a number, say in case of an emergency, the dial number would be of three digits. Similarly, there will be different cases like dialing a landline number or a mobile number or some service number or some toll-free number etc.
So, here ‘DIAL_NUMBER’ method will be declared as an abstract method. Here, the functionality of this method is same, that is dialing a number. But the implementation could be different in different scenarios.
Program:
CLASS ZCL_TELEPHONE DEFINITION ABSTRACT. “Abstract Class”
PUBLIC SECTION.
METHODS: DIAL_NUMBER ABSTRACT. “Abstract Method”
METHODS: PICKUP_CALL.
METHODS: DROP_CALL. “Non-Abstract Methods”
METHODS: REJECT_CALL
ENDCLASS.
CLASS ZCL_SUBCLASS_TELEPHONE DEFINITION INHERITING FROM ZCL_TELEPHONE. ‘
PUBLIC SECTION.
METHODS DIAL_NUMBER REDEFINITION.
ENDCLASS.
CLASS ZCL_SUBCLASS_TELEPHONE IMPLEMENTATION.
METHOD DIAL_NUMBER.
…
ENDMETHOD.
ENDCLASS.
Advantages:
- Provide flexibility to add default operations with multiple flavors.
- Abstract classes allow us to partially implement the class.
- We can achieve Polymorphism by using an abstract class.
- We can achieve Dynamic Binding also. The object of an abstract class can be used as a reference, which further could be replaced by the concrete object at runtime, this is known as dynamic binding.
Precise and informative.Thanks much