Static Classes/Methods vs Objects/Instance Classes/Methods?

Hi,
I am reading "Official ABAP Programming Guidelines" book. And I saw the rule:
Rule 5.3: Do Not Use Static Classes
Preferably use objects instead of static classes. If you don't want to have a multiple instantiation, you can use singletons.
I needed to create a global class and some methods under that. And there is no any object-oriented design idea exists. Instead of creating a function group/modules, I have decided to create a global class (even is a abstract class) and some static methods.So I directly use these static methods by using zcl_class=>method().
But the rule above says "Don't use static classes/methods, always use instance methods if even there is no object-oriented design".
The book listed several reasons, one for example
1-) Static classes are implicitly loaded first time they are used, and the corresponding static constructor -of available- is executed. They remain in the memory as long as the current internal session exists. Therefore, if you use static classes, you cannot actually control the time of initialization and have no option to release the memory.
So if I use a static class/method in a subroutine, it will be loaded into memory and it will stay in the memory till I close the program.
But if I use instance class/method, I can CREATE OBJECT lo_object TYPE REF TO zcl_class then use method lo_object->method(), then I can FREE  lo_object to delete from the memory. Is my understanding correct?
Any idea? What do you prefer Static Class OR Object/Instance Class?
Thanks in advance.
Tuncay

@Naimesh Patel
So you recommend to use instance class/methods even though method logic is just self-executable. Right?
<h3>Example:</h3>
<h4>Instance option</h4>
CLASS zcl_class DEFINITION.
  METHODS add_1 IMPORTING i_input type i EXPORTING e_output type i.
  METHODS subtract_1 IMPORTING i_input type i EXPORTING e_output type i.
ENDCLASS
CLASS zcl_class IMPLEMENTATION.
  METHOD add_1.
    e_output = i_input + 1.
  ENDMETHOD.
  METHOD subtract_1.
    e_output = i_input - 1.
  ENDMETHOD.
ENDCLASS
CREATE OBJECT lo_object.
lo_object->add_1(
  exporting i_input = 1
  importing e_output = lv_output ).
lo_object->subtract_1(
  exporting i_input = 2
  importing e_output = lv_output2 ).
<h4>Static option</h4>
CLASS zcl_class DEFINITION.
  CLASS-METHODS add_1 IMPORTING i_input type i EXPORTING e_output type i.
  CLASS-METHODS subtract_1 IMPORTING i_input type i EXPORTING e_output type i.
ENDCLASS
CLASS zcl_class IMPLEMENTATION.
  METHOD add_1.
    e_output = i_input + 1.
  ENDMETHOD.
  METHOD subtract_1.
    e_output = i_input - 1.
  ENDMETHOD.
ENDCLASS
CREATE OBJECT lo_object.
lo_object->add_1(
zcl_class=>add_1(
  exporting i_input = 1
  importing e_output = lv_output ).
lo_object->subtract_1(
zcl_class=>subtract_1(
  exporting i_input = 2
  importing e_output = lv_output2 ).
So which option is best? Pros and Cons?

Similar Messages

  • How to access the parent class variable or object in java

    Hi Gurus,
    I encounter an issue when try to refer to parent class variable or object instance in java.
    The issue is when the child class reside in different location from the parent class as shown below.
    - ClassA and ClassB are reside in xxx.oracle.apps.inv.mo.server;
    - Derived is reside in xxx.oracle.apps.inv.mo.server.test;
    Let say ClassA and ClassB are the base / seeded class and can not be modified. How can i refer to the variable or object instance of ClassA and ClassB inside Derived class.
    package xxx.oracle.apps.inv.mo.server;
    public class ClassA {
        public int i=10;
    package xxx.oracle.apps.inv.mo.server;
    public class ClassB extends ClassA{
        int i=20;   
    package xxx.oracle.apps.inv.mo.server.test;
    import xxx.oracle.apps.inv.mo.server.ClassA;
    import xxx.oracle.apps.inv.mo.server.ClassB;
    public class Derived extends ClassB {
        int i=30;
        public Derived() {
           System.out.println(this.i);                  // this will print 30
           System.out.println(((ClassB)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassB
           System.out.println(((ClassA)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassA
        public static void main(String[] args) { 
            Derived d = new Derived(); 
    Many thanks in advance,
    Fendy

    Hi ,
    You cannot  access the controller attribute instead create an instance of the controller class and access the attribute in the set method
    OR create a static method X in the controller class and store the value in that method. and you can access the attribute by 
    Call method class=>X
    OR if the attribute is static you can access by classname=>attribute.
    Regards,
    Gangadhar.S
    Edited by: gangadhar rao on Mar 10, 2011 6:56 AM

  • Passing object references via methods

    Why is the JFrame object not being created in the following code:
    public class Main {
      public static void main(String[] args) {
        Main main = new Main();
        JFrame frame = null;
        main.createFrame(frame);  // <-- does not create the "frame" object
        frame.pack();
        frame.setVisible(true);
      private void createFrame(JFrame frame) {
        frame = new JFrame("createFrame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }Thanks.

    These explanations are great; real eye openers.
    OK. This could be a "way out in left field" question. I am just starting out with Java. But I want to ask:
    Objects are stored in the heap?
    Object references and primitives are stored on the stack?
    Adjusting heap size is straight-forward. A larger heap can store more/larger objects. What about stack sizes?
    C:\Dev\java -Xss1024k Main
    I assume this refers to method's stacks. But, what about object scoped, and class scoped, object references?
    public class Main {
      private static List list = new ArrayList(); // class scoped
      private JFrame frame = new JFrame();  // object scoped
      public static void main(String[] args) { ...... }
      private void createFrame() { .... }
    }How is the reference to list and frame stored, with regard to memory management?
    Do objects have stacks?
    Do classes have stacks?
    If not, how are the list and frame references stored (which helps me understand reference scoping).
    Would the overflow of a method stack (ex. via recurssion) also overflow the method's object and the method's class stacks?
    If these questions are stupid, "out of left field", don't matter, etc. Just ignore them.
    But the knowledge could help me avoid future memory related mistakes, and maybe pass a "Java Certified Developer" exam?
    My original question is already answered, so thanks to all.

  • Creating  a static method returning Logger Object inside class

    Hello,
    Instead of creating Logger Instance in every class , can i do like this way by creating a static method in some class returning a Logger object , and using that method for getting instance of Logger in another class through that method
    Regards
    Mayur Mitkari

    On a related note, if you want to make it simpler, never do this:
    if (a == true)Instead, just do if (a)It's pointless and cluttersome to use == or != with true or false.
    // wrong
    if (a == true)
    if (a != false)
    // right
    if (a)
    // wrong
    if (a == false)
    if (a != true)
    // right
    if (!a)Also, note that
    if (x) {
      return true;
    else {
      return false;
    }can be simplified to return x;If you do that and change your variable to something a bit more meaningful, like trueCount or numTrue or something, your code would be
    int trueCount = 0;
    if (a) trueCount++;
    if (b) trueCount++;
    if (c) trueCount++;
    return trueCount >= 2;which is about as simple and clear as it can get, IMHO. Using less code doesn't necessarily make the code simpler or clearer. The idea is that someone reading the code can easily understand what it does.
    And note that the above can be easily generalized to "Are there at least M true values in this array/list of N booleans?" and still be concise and clear.

  • Interfaces and methods of Object class

    JSL 2.0 states the following
    If an interface has no direct superinterfaces, then the interface implicitly
    declares a public abstract member method m with signature s, return type r,
    and throws clause t corresponding to each public instance method m with
    signature s, return type r, and throws clause t declared in Object, unless a
    method with the same signature, same return type, and a compatible throws
    clause is explicitly declared by the interface.
    But the following codes produces empty output
    package test;
    import java.lang.reflect.Method;
    public class TestIterface {
        public static void main(String [] args){
            Method [] methods=Y.class.getMethods();
            for(int i=0, n=methods.length;i<n;i++)
                System.out.println(methods);
    interface Y{
    What are the reasons of such behaviour?

    then the interface implicitly declares a public abstract member method
    "Implicit" means that it's implied that the interface declares those methods; unlike java.lang.Object, there is no interface from which all other interfaces descend. All interfaces at the "top" of the inheritance hierarchy are implied to expose at least the same methods as Object.
    Hope this helps...

  • Calling Instance Method in a Global Class

    Hi All,
    Please can you tell me how to call a instance method created in a global class in different program.
    This is the code which I have written,
    data: g_cl type ref to <global class>.
    call method g_cl -> <method name>
    I am not able to create Create object <object>.
    It is throwing the error message " Instance class cannot be called outside...."
    Please can anybody help me..
    *Text deleted by moderator*
    Thanks
    Sushmitha

    Hi susmitha,
    1.
    data: g_cl type ref to <global class>.
    2.
    Create object <object>.
    3.
    call method g_cl -> <method name>.
    if still you are getting error.
    then first check that method level and visibility in se24.
    1.if  level is static you can not call it threw object.
    2. if visibility is protected or private then you can not  call it directly.
    If still you are facing same problem please paste the in this thread so that i can help you better.
    Regards.
    Punit
    Edited by: Punit Singh on Nov 3, 2008 11:54 AM

  • How to synchronize a method for all instances of a class

    Hi,
    How to make a method synchronized for all instances of a class? If a simple method is synchronized, then multiple threads cannot access it at the same time. If we make the method as static, then we are making it synchronized at class level.How to make a synchronized method so that no two instances (objects) of a class can access it at the same?
    Thanks
    Neha

    Neha_Khands wrote:
    There is nothing wrong with that. Actually this question was asked in an interview. They didnt want to create a static method. They told me that synchronization can be achieved at instance level also. and for that we have to call some Class.getInstance().synchronied method inside constructor. Kind of a dumb question. First, synchronization does not occur "at a class level" or "at an instance level." Syncing is always the same--a single object's lock is obtained, which prevents any other threads from obtaining that lock. The only thing that makes it appear that there are special cases is that declaring a method synchronized obtains the lock associated with the instance or with the Class object for that class. But that's just syntactic sugar. The Class object lock is identical to the instance lock, which in turn is identical to a lock on some other arbitrary Object created just to serve as a lock. There's no such things as "locking the class" or "locking the instance."
    Second, and more important, making an instance method synced across all instances is a grotesquely artificial situation, IMHO, and if it were to ever come up, the right way to do it is to have that instance method call a static synchronized method.

  • Class methods vs. Instance methods

    When shall we use class methods instead of instance methods , and vice versa?
    By going through the Java Tutorial, it only says the following.
    A common use for static methods is to access static fields....
    I am definitely sure that class methods aren't just exist for accessing static fields of a class.
    PS. I understand that instance methods belong to the object that is instantiated and class methods belong to the class itself.

    Jay-K wrote:
    JoachimSauer wrote:
    P.S.: I wouldn't call them "class methods". They are called static methods in Java. It helps to stay with the common, widely-used terminology.Thanks, its good to know what the norms are.
    but i wonder why the Java Tutorial states it clearly "Class Methods" over here [http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html|http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html]
    Because strictly speaking that's what they are. They belong to classes, rather than instances of classes. The world-at-large, though, has found that term to be a bit ambiguous, especially when discussing fields - it's not uncommon to see instance variables referred to as "class variables" by newbies - so it's kind-of self-corrected.

  • How to call a method from a class without creating an instance fromthisclas

    I want to create a class with methods but I want to call methods from this class without creating an instance from this class. Is this possible?
    Is there in Java something like class methods and object methods????

    keyword 'static' my friend.
    public class foo {
    public static void bar {
    System.out.println ("hello");
    foo.bar()

  • Problem in calling method with object in another class

    Hi All,
    Please tell me the solution, I have problem in calling a method I am posting the code also
    First Program:-
    import java.io.*;
    public class One
    public One()
    System.out.println("One:Object created");
    public void display()
    System.out.println("One:executing the display method");
    static
    System.out.println("One:executing the static block");
    Second Program:-
    import java.io.*;
    public class Two
    public Two()
    System.out.println("Two:Object created");
    public static void main(String arg[])throws Exception
    System.out.println("Two:executing the main method");
    System.out.println("Two:loading the class and creating the object::One");
    Object o=Class.forName("One").newInstance();
    System.out.println(o);
    o.display(); //displaying error here in compile time.
    static
    System.out.println("Two:executing the static block");
    waiting for your answer,
    thanks in advance,bye.

    Hi All,
    Please tell me the solution, I have problem in
    calling a method I am posting the code also
    First Program:-
    import java.io.*;
    public class One
    public One()
    System.out.println("One:Object created");
    public void display()
    System.out.println("One:executing the display
    method");
    static
    System.out.println("One:executing the static
    block");
    Second Program:-
    import java.io.*;
    public class Two
    public Two()
    System.out.println("Two:Object created");
    public static void main(String arg[])throws
    Exception
    System.out.println("Two:executing the main
    method");
    System.out.println("Two:loading the class and
    creating the object::One");
    Object o=Class.forName("One").newInstance();
    System.out.println(o);
    o.display(); //displaying error here in compile
    time.
    static
    System.out.println("Two:executing the static
    block");
    waiting for your answer,
    hanks in advance,bye.the line
    o.display()
    could be written as
    ((One)o).display();

  • Can we call a static method without mentioning the class name

    public class Stuff {
         public static final int MY_CONSTANT = 5;
         public static int doStuff(int x){ return (x++)*x;}
    import xcom.Stuff.*;
    import java.lang.System.out;
    class User {
       public static void main(String[] args){
       new User().go();
       void go(){out.println(doStuff(MY_CONSTANT));}
    }Will the above code compile?
    can be call a static method without mentioning the class name?

    Yes, why do it simply?
    pksingh79 wrote:
    call a static method without mentioning the class name?For a given value of   "without mentioning the class name".
        public static Object invokeStaticMethod(String className, String methodName, Object[] args) throws Exception {
            Class<?>[] types = new Class<?>[args.length];
            for(int i=0;i<args.length;++i) types[i] = args==null?Object.class:args[i].getClass();
    return Class.forName(className).getDeclaredMethod(methodName,types).invoke(null,args);

  • Wrapper classes/ instance variables&methods

    can anyone provide me additional information on the wrapper classes.
    In addition, could someone please provide an explination of the- instance and class (variables+methods)

    Every primitive class has a wrapper class e.g.
    int - Integer
    float - Float
    long - Long
    char - Character
    etc. When a primitive is wrapped it becomes an object and immutable. Primitives are generally wrapped (either to make them immutable) or to be able to add them to the collections framework(sets, maps, lists which can only take objects, not primitives).
    An instance variable is a variable that each copy of the object you create contains, as is an instance method. Each instance you create (each copy of the object) contains its own copy of the variable and method.
    A class variable and method means that no matter how many objects you create, there will be one and only one copy of the variable and method.
    Hope this helps. Also see the java tutorial.

  • How do interfaces have methods of Object class

    Hi All,
    Please consider the following code snippet.
    public interface EmployeeService
        public void createEmployee(Employee emp);
        public Employee findEmployee(String empId);
    public class EmployeeServiceImpl implements EmployeeService
        public void createEmployee(Employee emp) { ................. }
        public Employee findEmployee(String empId) { ................. }
    }The above is a simple example where I have an employee object with two service methods to create and find an employee.
    Now the consider the following
    EmployeeService empService = new EmployeeServiceImpl();
    Employee emp = empService.findEmployee("1").So the above code helps me in finding an employee.
    Now, we know that you can only call those methods that are defined in the interface.
    My question is, if I use the empService you would be able to access the methods of the Object class (equals, hashCode, wait etc.)
    How does this happen? In the Jave API we know all class by default override the Object class, so how does it work with interfaces?
    Thanks in advance for the reply

    [JLS 6.4.4 The Members of an Interface Type|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4.4] says:
    If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface. It is a compile-time error if the interface explicitly declares such a method m in the case where m is declared to be final in Object.
    So, in short, those methods exist in interfaces because the JLS says they do.

  • Instance/Class Variables/Methods

    Can someone please give a CLEAR explanation on what is a Instance Variable, Instance Method, Class Variable, and Class Method? Thanks a lot!

    instance method and variable is one that requires an instance to be created before they can be used.
    Class method and variables don't need an instance. They have the static qualifier.
    For example
    public class Test {
        public String instanceVar;
        static public String classVar;
    }Now to use instanceVar you have to do this
    Test test = new Test();
    test.instanceVar = "";To use classVar
    Test.classVar = "";Another way of looking at it is that each instance of a class (created using new) has its own copy of instance variables.
    Multiple instances of a class however share the same copy of class variables.
    The same pretty much goes for methods.

  • Whats the difference between a class method and a instance method.

    I have a quiz pretty soon and one of the questions will be: "How does an instance method differ from a class method." I've tried looking this up but they gave me really complicated explanations. I know what a instance method is but not really sure what a class one is. Can someone post an example of a class method and try to explain what makes it so special?
    Edited by: tetris on Jan 30, 2008 10:45 PM

    Just have a look:
    http://forum.java.sun.com/thread.jspa?threadID=603042&messageID=3246191

Maybe you are looking for

  • FROM DATABASE INDX: What is this and how this it work?

    Hi, I have the following statements in one of the programs that I am modifying:     INDX_KEY-FLAG = 'SP'.     INDX_KEY-USERA = SY-UNAME.     IMPORT DATA_TABLE FROM DATABASE INDX(SD) ID INDX_KEY. What does the last statement mean? How is it able to fi

  • Using Decode Or Case Statement / Any Method

    Dear All, In my table Fields are EmpId TranYear TranMonth ApprovedBy ApprovedYear ApprovedMonth My Input parameters are 1. TranYear 2. TranMonth 3. Tag1 4. Tag2 My requirement is Tag1 Input are 0,1,2 Tag2 Inputs are 0,1,2 If Tag1 is 0 then checking T

  • Debug Flash Player

    I am very new to Flex development and have had no luck trying to install the ActiveX flash player. I believe that I am supposed to use the one that was supplied with Flex Builder 3 found in <install location>/Player/win. From what I have garnered fro

  • HT201210 Error 2003, what is this????

    I have reset my Iphone 3S and while reinstalling the software, from ITunes, I am getting this message unable to install Error 2003, Will someone help me to overcome this problem

  • Gdm depends on gnome-desktop [SOLVED]

    I have xfce and want to have a display manager so that I can automatically boot to the desktop. In (X)ubuntu I used to have gdm, so I would like to have that now too. The problem is that when I try to install gdm with pacman, gnome-desktop becomes a