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.

Similar Messages

  • 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

  • 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?

  • Bapi - class method-instance method

    can v tell from a given bapi, whether a particular bapi is a class method or an instance method by observing the code?

    Priya Madhavi wrote:
    > i mean the example in the code... with the syntax that u gave for both the types.
    I didn't get your point about syntax?
    May be check this link
    http://www.sapmaterial.com/bapi_example.html

  • How to call inner class method in one java file from another java file?

    hello guyz, i m tryin to access an inner class method defined in one class from another class... i m posting the code too wit error. plz help me out.
    // test1.java
    public class test1
         public test1()
              test t = new test();
         public class test
              test()
              public int geti()
                   int i=10;
                   return i;
    // test2.java
    class test2
         public static void main(String[] args)
              test1 t1 = new test1();
              System.out.println(t1.t.i);
    i m getting error as
    test2.java:7: cannot resolve symbol
    symbol : variable t
    location: class test1
              System.out.println(t1.t.geti());
    ^

    There are various ways to define and use nested classes. Here is a common pattern. The inner class is private but implements an interface visible to the client. The enclosing class provides a factory method to create instances of the inner class.
    interface I {
        void method();
    class Outer {
        private String name;
        public Outer(String name) {
            this.name = name;
        public I createInner() {
            return new Inner();
        private class Inner implements I {
            public void method() {
                System.out.format("Enclosing object's name is %s%n", name);
    public class Demo {
        public static void main(String[] args) {
            Outer outer = new Outer("Otto");
            I junior = outer.createInner();
            junior.method();
    }

  • Calling the super class method from the subclass

    Hi all,
    I have a question about inheritence and redefinition of methods. Is it possible to call the superclass implementation of a method which is redefined in the subclass in another method of the subclass?There are possbilities like creation of an explicit super class instance or delegating the super class method implementation to another method which is also protected etc. What i mean is, is there a direct way of calling it?We have ,me,   as the reference for the instance we have(which is the subclass instance in this case), is there also a way of pointing the superclass implementation(with super we can reference in the subclass redefinition, my question is if we have such a parameter in other methods of the subclass too)
    Thanks in advance
    Sukru

    Hi,
    The super reference can only be used in redefined methods to call superclass implementation . So probably what you can do is use upcasting and access the required superclass implementation. I can think of only this way...;-)
    Ex data lr_super type ref to cl_superclass
    lr_super = lr_subclass.
    lr_super->method().
    ~Piyush Patil

  • Passing select-options to class methods

    Hi,
    I want to pass a select-option filled in the selection screen by the user to a method of my class. Since select-options are hold as an internal table with fields sign option low high, and passing internal tables to methods require typing, what should I write as the name of this internal table type?
    For example;
    select-options: so_carid for spfli-carrid.
    I want to pass the contents of so_carid to my method defined in a class

    hI
    Triggering and Handling events
    At the moment of implementation, a class defines its:
             Instance events (using the EVENTS statement)
            Static events (using the CLASS-EVENTS statement)
    Classes or their instances that receive a message when an event is triggered at runtime and want to react to this event define event handler methods. Statement: METHODS
    CLASS IC1_VEICHLE DEFINATION.
    PUBLIC SECTION.
    METHOD CONSTRUCTOR IMPORTING
    EVENTS VEICHEL_CREATION.
    ENDCLASS
    CLASS LC1_VEICHLE IMPLIMENTATION.
    METHOD CONSTRUCTOR
    RAISE EVENT VEICHLE_CREATION.
    REWARD IF USEFULL

  • Is it possible to call a class method using pattern in ABAP editor.

    Hi,
         Is it possible to call a class method using pattern in ABAP editor.
    Thank U for Ur time.
    Cheers,
    Sam

    Yes,
    Click patterns.
    Then choose Abap objects patterns.
    Click on the Tick
    It will give a new screen
    Here Give the name of the class first.
    Then the object (instance of the calss)
    And finally the method ..
    it will give you the pattern
    Hope this helps.

  • Invoking Derived Class Method

    Hi pls go through the below code, can any one give me solution how to access the Derived class method in this Point.
    Note: In the below code , only in runtime we will come to know which Derived class method is going to invoke(So in runtime we will get Derived class name in the form of String). So Iam trying to Use Class.forName("Clas name") to create the instance of the Derived class and then type casting to base class.
    Why iam casting to base class is , since only in the run time we are geting the Derived class name.
    Result : iam geting the compiletime error says that no valid method fond in Mybase though it contains the reference of derived.
    abstract class MyBase
    public void display(int i)
    System.out.println(" Base class Method");
    class MyDerived extends MyBase
    public void display(String str)
    System.out.println("Derived class Mthode");
    class MyMain
    public static void main(String arg[])
    String DrivObj=arg[0];
    MyBase baseObj=(MyBase) Class.forName("DrivObj").newInstance();
    baseObj.display("SomeString"); }
    }

    The problem is, can not have subclass reference bcoz
    iam geting the subclass name only in the runtime and
    one more thing is cant touch my base and subclass to
    do changes as u said Your design is then definately very bad.
    , is there any other way to do
    it.Yes, you can use reflection to invoke the method.
    Kaj

  • Class-data versus data and methods versus class-methods in OO ABAP

    Hi
    I was going thorugh following OO ABAP code.
    CLASS vessel DEFINITION.
      PUBLIC SECTION.
        METHODS: constructor,
                 drive IMPORTING speed_up TYPE i,
                 get_id RETURNING value(id) TYPE i.
        CLASS-METHODS: start,
                       objects,
                       inheritance,
                       interfaces,
                       events.
      PROTECTED SECTION.
        DATA: speed TYPE i,
              max_speed TYPE i VALUE 100.
      PRIVATE SECTION.
        CLASS-DATA object_count TYPE i.
        DATA id TYPE i.
    ENDCLASS.
    Whats is difference between methods and class-methods ?
    What is the difference between data and class-data ?

    Hi Rajesh,
    There are two types of componenets in a class
    1)Static components
    2) Instance components
    Instance components exist for every instance of the class, while static exist only once for any number of instances of the class.
    Components of the class are methods, attributes, events etc.
    static attributes are represented by CLASS-DATA and instance attributes are represented by DATA.
    static methods hence are done by CLASS-METHODS and can access only static attributes.
    Instance methods are done by METHODS and can access any attribute.
    For eg: supposing that in a class, there is a static attribute. Suppose after one instance is created, we are setting this static attribute value as 10. Now we are creating another instance of the same class. Now when you try to display the value of this attribute, it will be 10.ie. it needs to be initialized once and can be shared between instances.
    Just go through this document..You will get nice info from this.
    http://esnips.com/doc/5c65b0dd-eddf-4512-8e32-ecd26735f0f2/prefinalppt.ppt
    http://esnips.com/doc/2c76dc57-e74a-4539-a20e-29383317e804/OO-abap.pdf
    If you want to go deeper, like object persistence and all, just refer this document.
    http://esnips.com/doc/92be4457-1b6e-4061-92e5-8e4b3a6e3239/Object-Oriented-ABAP.ppt
    Regards,
    SP.

  • Dynamic Call Function/Class Method

    Hi,
    I have a requirement for which I need your help.
    I want to Call a Method dynamically inside a program. how to do it?
    My another quary is that how to call more than one class method dynamicaly in the program one at a time, based on certain conditions.
    All the requirements mentioned above feels awakward to me, but are they feasible. Eagerly waiting for a reply.
    Regards,
    Pulokesh
    Moderator message - Cross post locked
    Edited by: Rob Burbank on Oct 26, 2009 9:48 AM

    Hello,
    you can call a Method like this where the name of the method is concatenated.
    CONCATENATE 'SC_' me->gf_scenario '_SAVE' INTO lf_method.
      CALL METHOD me->(lf_method).
    Than I can imagine to loop over a tabele with all the Method Call to be executes un there:
    Loop at gt_meth_calls into ls_meth_call.
       ls_meth_call-object_instance->(ls_meth_call-meth_name).
    endloop.
    The table should be structured such that the first component contains a reference to the instance and the second component will be the Method name to run.

  • Abstract class method polymorphically using constructors?

    how can i have a method defined in an abstract superclass call a constructor of the actual class running the method?
    abstract class A {
    public List getMultple() {
    List l = new ArrayList();
    for (short i=0;i<4;i++) {
    l.add(this());//<obviously this breaks
    return l
    or something like that. A won't run this method, but its children will...and they can call their constructors, but what do i put here to do that?
    i've tried a call back. an abstract method getOne() in the superclass forces each child to define that method and in each of those i return the results of a constructor. that works fine.
    the problem is i want to abstract this method out of each of these children classes cause its the exact same in each one, just using a different constructor to get multiple of each in a list. so if i use this callback method, then i am not saving the number of methods in each class, so why bother at all?
    any ideas?

    I still say you are coming at it from the wrong angle. A super class is not the way to go. What you are doing sounds like something very similar to something I did not too long ago.
    My requirement was that I had tab delimited text files filed with data that I had to parse. Each line would be used to instantiate one object, so a particular file could be used to instantiate, for example, a thousand objects of the same class. There were different types of files corresponding to different classes to instantiate instances of.
    Here is the design I ended up using.
    An object of class DataTextFileReader is instantiated to parse the text file and generate objects. It includes code for going line by line, handling bad lines and generating objects and reports. The constructor:
    public DataTextFileReader(File inputFile, LineParser<T> theLineParser)LineParser is an interface with one method:
    public T read(String line);When you call a load() method of the DataTextFileReader, it does its thing with the aid of the LineParser's read method, to which each line is passed, and stores the generated objects in an ArrayList. This can be returned by using another method. There are other methods for getting the reports, etc.
    Obviously, the LineParser chosen needs to have code appropriate for parsing the lines in question, so you have to choose and instantiate the right one.
    I find this design to work well. I arrived at it after spending hours giving myself headaches trying to come up with a design where there was a superclass roughly equivalent to the DataTextFileReader mentioned above, and classes extending this that fulfilled the duty of the LineParsers mentioned above... rather like what you are trying to do now.
    I did not care for the solution at first because it did not give me the "Ah, I am clever!" sensation I was expecting when I finally cracked the problem using inheritance, but I quickly came to think that it was much better OOD anyway.
    The LineParsers mentioned above are essentially embodiments of the Factory pattern, and I would recommend you do something similar in your case. Obviously your "constructors" all have to be different, so you should make a separate class for each of those. Then you can put the code that performs the query and loops to create loads of objects in another class called something like DatabaseDepopulator, using appropriate generics as in my example. Really it is the same problem, now that I look at it.
    This will also result in better separation of concepts, if you ask me. Why should the class constructor know how to parse a database result query, much less perform the query? It has nothing to do with databases (I presume). That is the job of an interpreter object.
    As a final note, remember... 95% of the time you feel like the language won't let you do what you want, it is because you shouldn't anyway.
    Drake

  • Access arrayobject from class method

    Hi,
    Can anyone tell me how to access the variables in an object array from a static method of the same class?
    In another class i create a object array
    MyClass[][] myObjectArray = new MyClass[3][3]
    In MyClass there is a declaration:
    public int myInt = 1
    and a class method:
    public static myMethod(){
    int intVar = "this is where i would like to read the value of myInt for each object, something like myObjectArray[0][0].myInt + myObjectArray[1][2].myInt, but it does not work"
    I guess something with "this" or "super", but dont know how.
    Thanks,
    /Thomas

    It should obviously be impossible to access any Instance
    in a class-method.
    You could pass it as an parameter though:
    public static void myMethod(MyClass[][] myCl)

  • Calling class method

    Hi,
    In classical report we click on the pattern and write the funciton module name there to get the import and export parameter of the fucntion.
    Can somebody tell me how to call the class method in the program with the parameters coming automatically .
    Thanks

    hi Arvind,
    Click on pattern.
    Choose ABAP object pattern radio button and press enter.
    You have four radio button-the first one call method is for your requirement.
    Enter the object instance name, class name and method name and press enter.
    You will get the call method for this instance of the class.
    Hope this helps.
    Regards,
    Richa

  • Error in class method

    Hi Friends,
    i am facing one problem while preparing code in proxy class method. i need to use same code so many places in my class method for that purpose  i was trying to use perform statements but system is giving syntax error 'Forms can not be defined in a class pool For this reason, there are no perform statements for internal FORM'S'.
    With out perform statements how to handle the repetative logic in same program. Any help will be highly appreciated.
    Thanks a lot in advance.

    If you are talking about global classes,
    then go to SE24 and create your class.
    In the class go to Methods tab, give a name to your method, Define it as a static method, if you want the values to be persisted and not specific to the instances that are created based on your class.
    Give the visibility as private, becuase you want these private methods only to be called in your class only.
    Then click on parameters and define your exporting and importing parameters.
    Double click on the method name and have your repetitive code there.
    YOu can call this method in other methods of the class using
    call method <method name>statement.
    Regards,
    Ravi

Maybe you are looking for