Preface – This post is part of the Differences in ABAP for Interviews series.
Table of Contents
Before discussing the differences between a Static attribute and Instance attribute, let’ have a quick introduction.
ABAP Class Attribute
Attributes are data objects of any data type within a class. The state of the class is defined by the content of the attribute. They are defined in the declaration section of the class.
Static attributes and instance attributes are two common types of attributes in the class.
Static attribute defines the state of the class and this state is common to all the instances of the class. Static attributes can be accessed before any instance of the class is created. For a static attribute, memory for it is allocated only once irrespective of the class instance. All the instances of the class share the same static attribute. Whenever there is a change in the value of this attribute, it is visible to all the instances of the class.
Syntax to declare a static attribute:
CLASS-DATA static_attribute TYPE data_type.
Instance attribute defines the instance-specific state of the object. An instance attribute can only be accessed using a reference variable. Memory for an instance attribute is allocated for each instance of the class i.e. if a class have 3 instance attributes and 2 instances of the class then 6 memory locations are allocated for this attribute. Whenever there is a change in the content of the attribute, this change is only visible to that instance which has changed it.
Syntax to declare an Instance attribute:
DATA instance_attribute TYPE data_type.
Difference between Static Attribute and Instance Attribute
Now, let’s have a look at their difference.
|Static Attribute||Instance Attribute|
|It can be called irrespective of the class instance.||It can be only called using object reference.|
|It is declared using CLASS-DATA keyword.||It is declared using DATA keyword.|
|Memory is allocated only once.||Memory is allocated for each instance.|
|Every instance shares the same static attribute.||Each instance has its own copy of the instance attribute.|
|Change to static attribute are reflected to all the instances of the class.||Change to an instance attribute is restricted to that particular instance.|
|It cannot be redefined in subclasses.||It can be redefined in subclasses.|