Local Class: Class created in SE38 as an ABAP program or in include is known as Local class. These are limited to the program in which it is defined or created. We cannot create objects for local class in other programs.
For every local class there will be
DEFINITION part and IMPLEMENTATION part.
Syntax for Definition and
Implementation of a local class.
Class <class_name> definition
<attributes>
<methods>
<events>
<constructor>
Endclass
Class <class_name> implementation.
<Method and Events are implemented
here>
Endclass
Syntax for Attributes Declaration
CLASS <class_name> DEFINITION.
DATA:
CLASS-DATA:
ENDCLASS
DATA:
Instance attributes are declared using the keyword DATA.
CLASS-DATA: Static attributes are declared using CLASS-DATA keyword.
Static attributes can be accessed with class name directly without creating the
instance of class.
Syntax for Method Declaration
CLASS <class_name> DEFINITION.
PUBLIC SECTION.
METHODS: <method_name>
IMPORTING
EXPORTING
CLASS-METHODS: <method_name>
IMPORTING
EXPORTING
PRIVATE SECTION.
PROTECTED SECTION.
ENDCLASS.
CLASS-METHOD: Static methods are declared using keyword CLASS-METHOD. Static
methods can be called using the class name without creating instance of class.
The attributes, methods and events are
declared under public, private, or protected visibility sections.
The functionality of method is written in
the implementation part of the class.
Creating a local class
Create a program in SE38 transaction and create
a local class definition in below way. Double click on class name to generate
implementation for definition part.
As we don’t have any methods in definition block the implementation will be empty.
To create the instance of a class a
reference must be declared for the class and object is created using CREATE
OBJECT statement.
With the new syntax there is no need to
declare the reference variable in DATA statement. With the NEW keyword both
declaration and CREATE OBJECT is not required.
OLD SYNTAX:
DATA: lo_obj TYPE REF TO <class
name>.
CREATE OBJECT lo_obj.
NEW SYNTAX:
DATA(lo_obj) = NEW <class name>( ).
Final Program
REPORT ztest_lcl.
CLASS lc_class DEFINITION.
PUBLIC SECTION.
DATA: lv_name1 TYPE char15. " Instance Attribute
CLASS-DATA: lv_name2 TYPE char15. " Static Attribute
ENDCLASS.
*&---------------------------------------------------------------------*
*& Class (Implementation) lc_class
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
CLASS lc_class IMPLEMENTATION.
ENDCLASS.
DATA: lo_obj TYPE REF TO lc_class.
CREATE OBJECT lo_obj.
*DATA(lo_obj) = NEW lc_class( ).
lo_obj->lv_name1 = 'Mark'.
lc_class=>lv_name2 = 'Anderson'.
WRITE: /'Instance Attribute:',lo_obj->lv_name1.
WRITE: /'Static Attribute:',lc_class=>lv_name2.
Output:
Instance Attribute: Mark
Static Attribute: Anderson