Difference between Static Method and Instance Method

Introduction

Before discussing the differences between an Instance method and Static method, let’ have a quick introduction.

A method is a block of codes that defines behaviour of an object of the class.  The method can access all the attributes of the class and can change the object data content.

Instance Method

Instance methods are defined using the METHODS statement. They get reinitialized every time an instance is created.  They can access all the attributes of the class and can trigger all its events. Instance methods have the flexibility to be inherited and can be redefined in subclasses.

Syntax to call an instance method: 

DATA instance_name TYPE REF TO class_name.

CREATE OBJECT instance_name.

CALL METHOD instance_name->instance_method(…).

Static Method

Static methods are defined using the CLASS-METHODS statement. They are called only once, when the program is started, irrespective to the class instance, and don’t get reinitialized throughout the execution of the program. They can access only static attributes and can trigger only static events of the class. They can be directly accessed by the class name itself.

Syntax to call a static method:

CALL METHOD class_name => static_method(..).

Now, let’s have a look at their difference.

Difference between Static Method and Instance Method

Instance Method Static Method
It requires instance. It doesn’t require instance.
It is an example of pass by value. It is an example of pass by reference.
It is defined using “METHODS”. It is defined using “CLASS-METHODS”.
Involves declaration of reference variable, instantiating the class and then calling the class. Can be directly accesses by the class name.
It can access all attributes of a class. It can access only static attribute of a class.
Cannot be redefined in sub classes. Can be redefined in sub classes.

Instance method over Static method

It sounds simpler to use Static methods as it does not involve long steps such as the declaration of a reference variable, instantiating the object and then calling the method. Static methods can be directly accessed by the class name.

But the question arises is that why instance methods are preferred over Static methods.

One of the important concepts of OOABAP is Polymorphism i.e. replacing the default implementation of the method with a specific implementation. Polymorphism is achieved by Method Redefinition. Since Static methods are operable on their own and are independent of the instances of the class, they cannot be overridden. Whereas Instance methods can be inherited to sub classes, they can be redefined with the specific implementation.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.