SAP Tech Pro

SAP Technical Blog
Topprice Price Comparison

Object Oriented Programming–Inheritance - Subclass can access public/protected components of superclass

Object Oriented Programming–Inheritance - Subclass can access public/protected components of superclass

This program will demonstrate:-

  • How to create a subclass from a superclass.
  • Subclass can access public/protected components( methods, attributes etc) of superclass.

 

This program contains superclass C1 and its subclass C2. Class C1 has the following components:-

Component

Nature

Section of Existence

Significance/action

NUM

Attribute

public

Value = 6

METH1

Method

Public

Displays value of NUM

METH2

Method

Protected

Displays:- “I am meth2”

NUM2

Attribute

Protected

Value = 7

Subclass of C1 is C2 which contains the following new components:-

Component

Nature

Section of Existence

Significance/action

M1

Method

public

  • Calls method meth1.
  • Calls method meth2
  • Displays value of variable num2.

In the START-OF-SELECTION block, an object OREF is created from C2 and the method M1 is called.The output of the program shows that method M1 of class C2 calls method METH1, then METH2 and finally displays variable NUM2.

This demonstrates that subclass C2 has access to the public and protected methods and attributes of superclass C1 and truly establishes the theme.

 


REPORT zstp_oo_abap.

CLASS c1 DEFINITION.
  PUBLIC SECTION.
    METHODS : meth1.
    DATA : num TYPE i VALUE 6.
  PROTECTED SECTION.
    DATA : num2 TYPE i VALUE 7.
    METHODS meth2.
ENDCLASS.

CLASS c1 IMPLEMENTATION .
  METHOD : meth1.
    WRITE:/5 num.
  ENDMETHOD.

  METHOD : meth2.
    WRITE:/5 ' I am meth2 '.
  ENDMETHOD.
ENDCLASS.

CLASS c2 DEFINITION INHERITING FROM c1.
  PUBLIC SECTION.
    METHODS : m1.
ENDCLASS.

CLASS c2 IMPLEMENTATION.
  METHOD m1.
    CALL METHOD : meth1, meth2.
    WRITE:/5 num2.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  DATA : oref TYPE REF TO c2.
  CREATE OBJECT oref.
  CALL METHOD : oref->m1.

Output -

image

Add comment

Before Buying, Compare Prices at Topprice.in

Topprice.in