When creating a class, instead of writing completely new data members and methods, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class or super class, and the new class is referred to as the derived class or sub class.
- An object of one class can acquire the properties of another class.
- Derived class inherits the data and methods of a super class. However, they can overwrite methods and also add new methods.
- The main advantage of inheritance is re-usability.
The inheritance relationship is specified using the ‘INHERITING FROM’ addition to the class definition statement.
Following is the syntax:
CLASS <subclass> DEFINITION INHERITING FROM <superclass>.
Example
Report ZINHERITAN_1. CLASS Parent Definition. PUBLIC Section. Data: w_public(25) Value 'This is public data'. Methods: ParentM. ENDCLASS. CLASS Child Definition Inheriting From Parent. PUBLIC Section. Methods: ChildM. ENDCLASS. CLASS Parent Implementation. Method ParentM. Write /: w_public. EndMethod.
ENDCLASS.
CLASS Child Implementation. Method ChildM. Skip. Write /: 'Method in child class', w_public. EndMethod. ENDCLASS. Start-of-selection. Data: Parent Type Ref To Parent, Child Type Ref To Child. Create Object: Parent, Child. Call Method: Parent→ParentM, child→ChildM.
The above code produces the following output:
This is public data Method in child class This is public data
Redefining Methods in Sub Class
The methods of the super class can be re-implemented in the sub class. Few rules of redefining methods:
- The redefinition statement for the inherited method must be in the same section as the definition of the original method.
- If you redefine a method, you do not need to enter its interface again in the subclass, you need only the name of the method.
- Within the redefined method, you can access components of the direct super class using the super reference.
- The pseudo reference super can only be used in redefined methods.
Example
Report Zinheri_Redefine. CLASS super_class Definition. Public Section. Methods: Addition1 importing g_a TYPE I g_b TYPE I exporting g_c TYPE I. ENDCLASS. CLASS super_class Implementation. Method Addition1. g_c = g_a + g_b. EndMethod. ENDCLASS. CLASS sub_class Definition Inheriting From super_class. Public Section. METHODS: Addition1 Redefinition. ENDCLASS. CLASS sub_class Implementation. Method Addition1. g_c = g_a + g_b + 10. EndMethod. ENDCLASS. Start-Of-Selection. Parameters: P_a Type I, P_b TYPE I. Data: H_Addition1 TYPE I. Data: H_Sub TYPE I. Data: Ref1 TYPE Ref TO sub_class. Create Object Ref1. Call Method Ref1→Addition1 exporting g_a = P_a g_b = P_b Importing g_c = H_Addition1. Write:/ H_Addition1.
After executing F8, if we enter the values 9 and 10, the above code produces the following output −
Redefinition Demo 29
No comments:
Post a Comment