Skip to Content

can we access public method of a child class specific method by using parent class object ?

hi to all,

i was trying to access the public method of child class specific method ,by using Parent class reference object by using narrow casting but i was unable to access .

so how can i access public method of a child class by using parent class referred object?

if poss

Add comment
10|10000 characters needed characters exceeded

  • Follow
  • Get RSS Feed

2 Answers

  • Aug 10, 2018 at 12:16 PM
    CAST class_child( parent )->child_method( ).
    data child type ref to class_child.
    child ?= parent.
    child->child_method( ).

    Add comment
    10|10000 characters needed characters exceeded

    • I have given you a code snippet. I'm not quite sure what you've failed to understand.

      Perhaps this will make it clear.

      CLASS lcl_parent DEFINITION.
      CLASS lcl_child DEFINITION INHERITING FROM lcl_parent.
          METHODS child_method.
        METHOD child_method.
          WRITE 'Child method called'.
        DATA parent TYPE REF TO lcl_parent.
        CREATE OBJECT parent TYPE lcl_child.
        DATA child TYPE REF TO lcl_child.
        child ?= parent.
        child->child_method( ).

      If you cast the parent reference variable to a reference variable that is the type of reference to the child class, then you have access to methods defined on the child class. (Assuming the parent is actually a child instance).

  • Aug 10, 2018 at 10:01 AM

    When narrow casting we cannot directly call the child class method. you need to dynamically call the method. Please make sure that it's narrow casted otherwise, you will run into short dumps.

    for ex: call method parent_class_ref->('child_specific_method').

    In this example compiler do not check the existence of child_specific_method against parent_class_ref during compile time.

    Hope this helps..


    Add comment
    10|10000 characters needed characters exceeded

    • You're adopting less than good practice and adding a weakness to your code.

      If you use this approach, and the method name changes, you get a runtime error. If you use the approach I suggested, you get a syntax error.

      Syntax errors are easy, quicker and cheaper to fix than runtime errors.