2009 Sep 24 9:45 PM
Let's say we have a superclass, zcl_animal. It has subclasses zcl_cat and zcl_dog with methods meow() and bark() respectively.
Let's say we set up an internal table called it_animals of type ref to zcl_animal.
I create a number of cats and dogs and append their refs into it_animals.
Furthermore,
lo_animal is type ref to zcl_animal
lo_cat is type ref to zcl_cat
lo_dog is type ref to zcl_dog
Now I loop through animal into the generic lo_animal object
Is there anyway for lo_animal to tell what subclass (cat or dog) it is so I can cast it appropriately.
(without trial and error casting )?
Thanks...
...Mike
2009 Sep 24 9:50 PM
You can use the RTTS to get the class name and get to know which subclass it is.
Method get_class_name of class CL_ABAP_CLASSDESCR.
Or, You can create an additional column in internal table which carries the name of the object as well.
Regards,
Naimesh Patel
Let's say we have a superclass, zcl_animal. It has subclasses zcl_cat and zcl_dog with methods meow() and bark() respectively.
Let's say we set up an internal table called it_animals of type ref to zcl_animal.
I create a number of cats and dogs and append their refs into it_animals.
Furthermore,
lo_animal is type ref to zcl_animal
lo_cat is type ref to zcl_cat
lo_dog is type ref to zcl_dog
Now I loop through animal into the generic lo_animal object
Is there anyway for lo_animal to tell what subclass (cat or dog) it is so I can cast it appropriately.
(without trial and error casting )?
Thanks...
...Mike
2009 Sep 24 9:50 PM
You can use the RTTS to get the class name and get to know which subclass it is.
Method get_class_name of class CL_ABAP_CLASSDESCR.
Or, You can create an additional column in internal table which carries the name of the object as well.
Regards,
Naimesh Patel
2009 Sep 24 9:56 PM
One more thought. (I haven't tested it)
You can create a protected method say ACTION( ) in your class ZCL_ANIMAL. Redefine this method in all subclasses. In the redefinition of method ACTION( ) in subclass ZCL_CAT, call method ME->MEOW( ).
This way, your application would not know, which sub-object it is dealing with. It would call the ACTION method and action would decide what to call from Sub-class.
Regards,
Naimesh Patel
2009 Sep 24 10:03 PM
Thanks - your first response was what I was looking for.
Redefinition (which I have a handle on) does not work in my
general case of the underlying problem, as some of the animals,
using this example, are giraffes and do not make a sound
(ie many of our methods won't be applicable across all subclasses)
Thanks for your help
...Mike
2009 Sep 26 11:25 PM
Hi,
your reference to Giraffe made me think you might need delegation instead of inheritance.
(i.e. STRATEGY PATTERN e.g. at http://sourcemaking.com/design_patterns/strategy).
regards,
Jacques Nomssi Nzali
| User | Count |
|---|---|
| 3 | |
| 1 | |
| 1 | |
| 1 | |
| 1 | |
| 1 | |
| 1 | |
| 1 | |
| 1 | |
| 1 |