Declaring static methods.

I have some questions about declaring a method as static. If I first write a paragraph about my understanding so far, followed by a code snippet hopefully somebody can help me out.
It is my understanding (limited) that only one class is loaded by the classloader. When creating an object, all its parameters are stored, but each object does not have its own copy of the methods its class defines, each method. If a method is declared as static then you do not have to create an instance of this class to call this method.
Code
/** Get table of codes.
      * @return <code>Hashtable</code> populated with clinical code values.
    public Hashtable getCodeHashtable(HttpServletRequest request) {
        Hashtable htResults = new Hashtable();
        try {
            SpParameter[] spOut = {
                new SpParameter(OracleTypes.CURSOR, 0)//po_cur_data
             HOUtils utils = new HOUtils();
            UtilDBquery db = utils.getUtilDBquery(request);
            htResults = db.runGeneralStoredProcedureThrowsExceptions(null, spOut, SP_CodeList, null, true, true);
        } catch (Exception e){
             e.printStackTrace();
        return htResults;
Questions
1) If each object does not carry around its own copy of the methods associated with its class, how does the jvm know which object is calling a method?
2) In the above code snippet, if I were to make the method static would this have implications if 2 people were to browse to the same page on the app server and run this method at the same time?
Thanks for any replies.

1) If each object does not carry around its own copy of the methods
associated with its class, how does the jvm know which object is
calling a method?Each object stores one single pointer to its class description. The class
description contains all the methods (also the static ones). This is a bit
of a simplification but basically that's all there is to it. When you call
a method, the address of the method is looked up in that class description
and it's invoked. For non static methods there's a hidden parameter,
called 'this' so the method always 'knows' which object it (the method)
is invoked on. For static methods that hidden parameter simply isn't
present.
2) In the above code snippet, if I were to make the method static
would this have implications if 2 people were to browse to the same
page on the app server and run this method at the same time?Who knows? This all depends whether or not the method (static or not)
is reentrant, i.e. does the method have side effects? Does the method
needs to be synchronized?
kind regards,
Jos

Similar Messages

  • Why interfaces can not declare static methods?

    Why interfaces can not declare static methods?

    Why are you shouting?
    Is your internet broken?
    [http://www.google.co.uk/search?q=interface+static+methods+java] 2,440,000 hits.

  • Static methods vs instant methods

    hi to all abap gurus
    thanks in advance
    all of the objects in the class can acess its its static attributes . and if u change the static attribute in an  object the change is visible in all other objects in the calsssss.
    can u pls expain this and tell the diffrence bewteen static and instance metod s?

    Hi,
    <b>Instance Method</b>
    You can declare instance methods by using the METHODS statement. They play a very important role as they can access all of the attributes of a class and can trigger all of the events of the class.
    <b>Static Methods</b>
    You can declare static methods by using the CLASS-METHODS statement. They are important and can only access static attributes and trigger static events.
    <b>STATIC METHODS</b>
    CAN ONLY USE STATIC COMPONENTS IN THEIR IMPLEMENTATION PART
    CAN BE CALLED USING THE CLASS
    Static methods (also referred to as class methods) are called using CALL METHOD <classname>=><class_method>.
    If you are calling a static method from within the class, you can omit the class name.
    You access static attributes using <classname>=><class_attribute>
    Regards,
    Padmam.

  • Implementation of static methods in Custom Controls

    I'm using Custom Java Controls to implement business objects in a workshop web application.
    I've designed a number of static methods into the object model for logically static operations (i.e. operations related to the Business object but not requiring an instance).
    Since workshop generates the control interface as a java interface, it is not possible to declare static methods on the control interface. I have tested implementing the interface as an abstract class and setting @editor-info:code-gen control-interface="false" on the control. This seems to work, but then we lose code generation.
    Other options include:
    - Put the static method on the Impl and call directly (don't like this, breaks encapsulation)
    - Make it non-static (don't like this, prevents compiler checks for refs to non-static members)
    Has anyone found an elegant way to do this in workshop without losing code gen features? Any ideas welcome...
    TIA
    Jim

    Please guys someone tell me the answer for this question. I guess its a valid question, though I feel that the answer to this question must be quiet easy since somewhere the methods must have been getting implemented.
    Please let me know who does that and how and when!!!
    Hoping for an explanation to this now

  • Interfaces and static methods

    Hi All,
    Does anyone know why you can't declare static methods in an interface? Is there a way round this problem?
    Cheers...

    But this won't:public class StijnsClass
      public static void aMethod()
        System.out.println("StijnsClass.aMethod()");
      public static void main(String[] arg)
        StijnsClass stijnsInstance = new StijnsSubClass();
        stijnsInstance.aMethod();
        System.out.println("Nothing else to say, here?");
    class StijnsSubClass extends StijnsClass
      public static void aMethod()
        System.out.println("StijnsSubClass.aMethod()");
        super.aMethod(); // Wrong!!!
    }You will get:
    "StijnsClass.java:21: non-static variable super cannot be referenced from a static context".
    If you remove static from the subclass method definition, you will get:
    "StijnsClass.java:18: aMethod() in StijnsSubClass cannot override aMethod() in StijnsClass; overridden method is static"
    That's the point. You aren't extending the method; you are only hiding it. To make it work, both methods must be instance methods, ergo, static methods cannot be extended.

  • Purpose of declaring the method or class or static and as instance

    what is the purpose of declaring a method in a class or the class itself as static.
    Does it mean we cannot create a copy of that class or method if we declare it as static.
    if so then why do they dont want that class to be created as a copy ?
    Why do they want to declare a class as static
    please provide some conceptual undersatnding regarding the static and instance class with one example

    Static methods are often used for the implementation of utility methods. Please have a look at the class CL_ABAP_CHAR_UTILITIES for example.
    You use the methods of this class in the same way as you would use a function in ABAP (like
    LINES( itab )
    ). You use it in a static way because the functionality is always the same no matter in what context you are calling the function.
    The purpose of instance methods is that their logic is in some way related to an attribute of the object instance that you use to call it.
    For example, you create an instance of object PO (a purchase order) called MY_PO. Then the method
    MY_PO->ADD_POSITION
    would add a position to a concrete PO that has a unique number etc. But if the object has a static method DELETE_POSITION then it just deletes the current position of a PO, regardless on which concrete PO you are acting at the moment.
    I hope this clarifies it for you.
    Regards,
    Mark

  • Variables declared in static methods

    Hi,
    I've got a question. Are variables (primitive and Objects) declared inside
    static methods stored in a same memory space or are the stored separately?
    I'm creating a helper class that contains static methods that canno be placed in any object in my object map.
    For example
    public static String SampleMethod(String passedString)
    String str = new String(passedString);
    ...do some more processing and sleeping
    return str;
    Let's say Object1 and Object2 make a call to SampleMethod. Object1 passes "Object1" and right before the Object1's SampleMethod returns str, Object2 makes a call passing "Object2". What would be the value of str for Object1's SampleMethodCall?
    Thanks :)

    If speaking about class members, then static members are stored in one place and are properties of the class, when non-staic members are stored in an object's memory and a properties of an object.
    However in your sample it's not the case.
    Local variables of a method are most likely allocated on registers or on stack (thus being rather properties of the call to a method).
    Thus in your case calls to SampleMethod done by Object1 and Object2 simultaneously (if you managed to do this in two different threads) will use different memory (most likely in threads' own stacks).
    As for calls to "new String" inside your method, the new string memory will be allocated dynamically each time the new operator is called, thus producing two different objects. The references to them will be stored in two local variables of two independent calls.
    Finally, Object1 will get a copy of "Object1" and Object2 will get a copy of "Object2", as expected.
    Vit

  • Compilation error while calling static method from another class

    Hi,
    I am new to Java Programming. I have written two class files Dummy1 and Dummy2.java in the same package Test.
    In Dummy1.java I have declared a static final variable and a static method as you can see it below.
    package Test;
    import java.io.*;
    public class Dummy1
    public static final int var1= 10;
    public static int varDisp(int var2)
    return(var1+var2);
    This is program is compiling fine.
    I have called the static method varDisp from the class Dummy2 and it is as follows
    package Test;
    import java.io.*;
    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    and when i compile Dummy2.java, there is a compilation error <identifier > expected.
    Please help me in this program.

    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    }test+=Dummy1.varDisplay(var3);
    must be in a method, it cannot just be out somewhere in the class!

  • How to call a static method from an event handler

    Hi,
       I'm trying to call a static method of class I designed.  But I don't know how to do it.  This method will be called from an event handler of a web dynpro for Abap application.
    Can somebody help me?
    Thx in advance.
    Hamza.

    To clearly specify the problem.
    I have a big part code that I use many times in my applications. So I decided to put it in a static method to reuse the code.  but my method calls functions module of HR module.  but just after the declaration ( at the first line of the call function) it thows an exception.  So I can't call my method.

  • Calling a non-static method from another Class

    Hello forum experts:
    Please excuse me for my poor Java vocabulary. I am a newbie and requesting for help. So please bear with me! I am listing below the program flow to enable the experts understand the problem and guide me towards a solution.
    1. ClassA instantiates ClassB to create an object instance, say ObjB1 that
        populates a JTable.
    2. User selects a row in the table and then clicks a button on the icon toolbar
        which is part of UIMenu class.
    3. This user action is to invoke a method UpdateDatabase() of object ObjB1. Now I want to call this method from UIMenu class.
    (a). I could create a new instance ObjB2 of ClassB and call UpdateDatabase(),
                                      == OR ==
    (b). I could declare UpdateDatabase() as static and call this method without
         creating a new instance of ClassB.With option (a), I will be looking at two different object instances.The UpdateDatabase() method manipulates
    object specific data.
    With option (b), if I declare the method as static, the variables used in the method would also have to be static.
    The variables, in which case, would not be object specific.
    Is there a way or technique in Java that will allow me to reference the UpdateDatabase() method of the existing
    object ObjB1 without requiring me to use static variables? In other words, call non-static methods in a static
    way?
    Any ideas or thoughts will be of tremendous help. Thanks in advance.

    Hello Forum:
    Danny_From_Tower, Encephalatic: Thank you both for your responses.
    Here is what I have done so far. I have a button called "btnAccept" created in the class MyMenu.
    and declared as public.
    public class MyMenu {
        public JButton btnAccept;
         //Constructor
         public MyMenu()     {
              btnAccept = new JButton("Accept");
    }     I instantiate an object for MyMenu class in the main application class MyApp.
    public class MyApp {
         private     MyMenu menu;
         //Constructor     
         public MyApp(){
              menu = new MyMenu();     
         public void openOrder(){
               MyGUI MyIntFrame = new MyGUI(menu.btnAccept);          
    }I pass this button all the way down to the class detail02. Now I want to set up a listener for this
    button in the class detail02. I am not able to do this.
    public class MyGUI {
         private JButton acceptButton;
         private detail02 dtl1 = new detail02(acceptButton);
         //Constructor
         public AppGUI(JButton iButton){
         acceptButton = iButton;
    public class detail02{
        private JButton acceptButton;
        //Constructor
        public detail02(JButton iButton){
          acceptButton = iButton;
          acceptButton.addActionListener(new acceptListener());               
       //method
        private void acceptListener_actionPerformed(ActionEvent e){
           System.out.println("Menu item [" + e.getActionCommand(  ) + "] was pressed.");
        class acceptListener implements ActionListener {       
            public void actionPerformed(ActionEvent e) {
                   acceptListener_actionPerformed(e);
    }  I am not able to get the button Listener to work. I get NullPointerException at this line
              acceptButton.addActionListener(new acceptListener());in the class detail02.
    Is this the right way? Or is there a better way of accomplishing my objective?
    Please help. Your inputs are precious! Thank you very much for your time!

  • Force Derived Class to Implement Static Method C#

    So the situation is like, I have few classes, all of which have a standard CRUD methods but static. I want to create a base class which will be inherited so that it can force to implement this CRUD methods. But the problem is, the CRUD methods are static. So
    I'm unable to create virtual methods with static (for obvious reasons). Is there anyway I can implement this without compromising on static.
    Also, the signature of these CRUD methods are similar.
    E.g. ClassA will have CRUD methods with these type of Signatures
    public static List<ClassA> Get()
    public static ClassA Get(int ID)
    public static bool Insert(ClassA objA)
    public static bool Update(int ID)
    public static bool Delete(int ID)
    ClassB will have CRUD signatures like
    public static List<ClassB> Get()
    public static ClassB Get(int ID)
    public static bool Insert(ClassB objB)
    public static bool Update(int ID)
    public static bool Delete(int ID)
    So I want to create a base class with exact similar signature, so that inherited derived methods will implement their own version.
    For E.g. BaseClass will have CRUD methods like
    public virtual static List<BaseClass> Get()
    public virtual static BaseClassGet(int ID)
    public virtual static bool Insert(BaseClass objBase)
    public virtual static bool Update(int ID)
    public virtual static bool Delete(int ID)
    But the problem is I can't use virtual and static due to it's ovbious logic which will fail and have no meaning.
    So is there any way out?
    Also, I have few common variables (constants) which I want to declare in that base class so that I don't need to declare them on each derived class. That's why i can't go with interface also.
    Anything that can be done with Abstract class?

    Hi,
    With static methods, this is absolutely useless.
    Instead, you could use the "Singleton" pattern which restrict a class to have only one instance at a time.
    To implement a class which has the singleton pattern principle, you make a sealed class with a private constructor, and the main instance which is to be accessed is a readonly static member.
    For example :
    sealed class Singleton
    //Some methods
    void Method1() { }
    int Method2() { return 5; }
    //The private constructor
    private Singleton() { }
    //And, most importantly, the only instance to be accessed
    private static readonly _instance = new Singleton();
    //The corresponding property for public access
    public static Instance { get { return _instance; } }
    And then you can access it this way :
    Singleton.Instance.Method1();
    Now, to have a "mold" for this, you could make an interface with the methods you want, and then implement it in a singleton class :
    interface ICRUD<BaseClass>
    List<BaseClass> GetList();
    BaseClass Get(int ID);
    bool Insert(BaseClass objB);
    bool Update(int ID);
    bool Delete(int ID);
    And then an example of singleton class :
    sealed class CRUDClassA : ICRUD<ClassA>
    public List<ClassA> GetList()
    //Make your own impl.
    throw new NotImplementedException();
    public ClassA Get(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Insert(ClassA objA)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Update(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Delete(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    private CRUDClassA() { }
    private static readonly _instance = new CRUDClassA();
    public static Instance { get { return _instance; } }
    That should solve your problem, I think...
    Philippe

  • Static methods

    Is creating a static method frowned upon in OO development? Is it only a matter of convenience by not having to instantiate?
    Any insight is appreciated.
    --Gregory
    quote: Don't throw away the old bucket until you know whether the new one holds water.

    Regardless of how many objects you have created, there is only 1 copy of the static variables in the memory. Its not just a matter of convenience but is used in certain conditions based on some requirements. A good example would be Singleton. There already is a kind of Singleton class in the standard Java class libraries:
    the Math class. This is a class that is declared final and all methods are declared static, meaning that the class cannot be extended. The purpose of the Math class is to wrap a number of common mathematical functions such as sin and log in a class-like structure, since the Java language does not support functions that are not methods in a class. You can use the same approach to a Singleton pattern, making it a final class. You can�t create any instance of classes like Math, and can only call the static
    methods directly in the existing final class.
    Another approach, suggested by Design Patterns, is to create Singletons using a static method to issue and keep track of instances. To prevent instantiating the class more than once, we make the constructor private so an instance can only be created from within the static method of the class.
    Hope that helps
    &#9824

  • Forcing implementation of an inherited static method/field?

    Suppose I have some classes - BlueAction, RedAction etc - extending an abstract base class called BaseAction. I put an abstract method called getColour() in BaseAction, and implement it in all the classes that extend it, so BlueAction returns blue, and so on. Fine.
    I now want to use a class loader to get their colour, but crucially, I don't want to instantiate them, so instance methods are out.
    If you could declare abstract static methods, I'd do that, and be assured that every implementation of BaseAction contained the necessary info. Obviously you can't do this.
    I think I could just put a static method or field in each one, and access that via something like Class.getField("COLOUR")but then there's nothing to force me to put that code into each implementation.
    Is there anything clever I can do?
    Cheers,
    Rob
    Edited by: arewenotmen on Jun 20, 2008 3:51 AM

    baftos wrote:
    I guess it should be possible. Me, I did play with runtime annotations, but I am scared like hell
    of compile time annotation. My reasons, but maybe I am wrong:All good reasons.
    - Modify the build process to use APT instead of javacYou could use in -nocompile mode and add a task to the build script.
    - Writing annotation processors, big overheadI had a play, was not too hard to get started with, but then it started to get wierd and data I expected was not being returned.
    - Using com.sun classes in the processors instead of java/javax classes (subject to change?)Java 6 has the javax.annotations package (also works with javac rather than a different tool), but this seams less powerful than apt.
    A fair few things now mean the "don't touch the com.sun package" rule is being eroded. The httpd is in it as well.

  • Trying to understand Static methods

    Hi all,
    I am trying to learn a little bit about static methods and hope that someone here can help me understand it better. My understanding of static methods is that they exist only once (More like global methods). This tells me that usage of static methods should be used with care as they are likely to cause problems in cases where multiple users try to access a static object at the same time.
    I am looking at a piece of code that had me thinking for a bit. I cant post the code itself but here is an example of how the code is structured
    The first class declares a couple of non static arrays and makes them available via the getters and setters. It also has one method that calls a static method in another class.
    package com.tests.statictest;
    import java.util.ArrayList;
    public class ClassA{
         ArrayList arrayList1 = new ArrayList();
         ArrayList arrayList2 = new ArrayList();
         public ClassA(){
              arrayList1.add("TEST1");
              arrayList1.add("TEST2");
              arrayList2.add("Test3");
              arrayList2.add("Test4");
         ArrayList getArrayList1(){
              return arrayList1;
         ArrayList getArrayList2(){
              return arrayList2;
         ArrayList getJoinedArrayList(){
              return ClassB.joinArrays(arrayList1,arrayList2);
    }The second class contains the static method that is called by the above class to join the two arrays. This class is used by many other classes
    package com.tests.statictest;
    import java.util.ArrayList;
    public class ClassB{
         public static ArrayList joinArrays(ArrayList list1, ArrayList list2){
              ArrayList list3 = new ArrayList();
              list1.addAll(list2);
              return list1;
    }And here is my test class
    package com.tests.statictest;
    public class ClassC{
          public static void main(String args[]){
               ClassA classA = new ClassA();
              System.out.println(classA.getArrayList1());
              System.out.println(classA.getArrayList2());
              System.out.println(classA.getJoinedArrayList());
         }The output to the above program is shown below
    [TEST1, TEST2]
    [Test3, Test4]
    [TEST1, TEST2, Test3, Test4]My question for the above is that i am wondering if the above is safe. Can you think of situations where the above is not recommended. What exactly would happen if ten instances of ClassA threads are executed at the same time? Woulnt the static method in ClassB corrupt the data?

    ziggy wrote:
    Hi all,
    I am trying to learn a little bit about static methods and hope that someone here can help me understand it better. My understanding of static methods is that they exist only once (More like global methods). This tells me that usage of static methods should be used with care as they are likely to cause problems in cases where multiple users try to access a static object at the same time. There is no such thing as a "static object" in Java. The word "static" simply means "belonging to a class as a whole, rather than an individual instance."
    My question for the above is that i am wondering if the above is safe. Can you think of situations where the above is not recommended. What exactly would happen if ten instances of ClassA threads are executed at the same time?ClassA isn't a thread, so it can't be "executed", per se.
    Woulnt the static method in ClassB corrupt the data?"Staticness" doesn't have anything to do with it; the issue at hand is operations on a shared data structure, which is a concern whether you're dealing with static or non-static members. There is nothing inherent in ClassB that will "corrupt" anything, however.
    ~

  • Static method

    If I'm trying to write a method that accepts a String argument and prints it on the screen, but the method itself is supposed to return nothing, what exactly does that mean???
    This is the question itself:
    Write the definition of a class� Telephone . The class� has no constructors� and one static� method� printNumber . The method� accepts a String�argument� and prints it on the screen. The method� returns nothing.
    However, all I really am asking for is maybe some tips on understanding the concept itself. I've been looking through the tutorials online, but I just haven't found anything that explains this outright.
    To give an idea of where I am going completely, embarassingly wrong, here is what I tried to write (which I know!! it's probably far off!):
    import java.util.Scanner;
    public class Telephone
    void printNumber ()
    String lineIn;
    Scanner scan = new Scanner(System.in);
    lineIn = scan.nextLine();
    System.out.println(lineIn);
    Now please, laugh quietly to yourself and then help :P
    Thanks!

    the method itself is supposed to return nothing, what exactly
    does that mean???
    Now please, laugh quietly to yourself and then help
    :P
    Thanks!"return nothing" most probably means that the method has a void return type, and no return statement in the body of the method. Looks like you got that part right in your code.
    I would guess that the other part would be solved by adding the static key word to your method declaration. It should also probably be public, so that other classes can call it.
    So:
    public static void printNumber()
       // body of method goes here
    }Good luck,
    RD-R
    � {�
    Mon Mar 07 00:38:07 EST 2005
    Pseudo-random saying number 525 of 635
    A limerick packs laughs anatomical
    Into space that is quite economical.
            But the good ones I've seen
            So seldom are clean,
    And the clean ones so seldom are comical.

Maybe you are looking for

  • Weird custom menu behavior in 8.2

    I'm in charge of upgrading a large project from LV 7.1 to 8.2 and I ran into several problems but was able to resolve them except 2 major ones (not including the crashing tables and indices in self-indexing while loops). 1) Our custom menu now seems

  • Can I convert my internal hard drive to an external hard drive

    I have an 80 GB hard drive that was in my MacBook.  What do I have to do to convert it to an external hard drive?  Thanks

  • Nokia C7 Phone Start-Up Failed

    A good friend of mine has a Nokia C7.  He and I both used to use SPB Mobile Shell, but I no longer do.  However, my friend is still using the SPB software. Sometimes when my friend turns on his phone, the usual Nokia information appears, then the "lo

  • Xw6200 workstatio​n 1gb sticks not working

    Hi guys how you doing. I registered on these forums due to a little problem i had today. I recently purchased memory for my xw6200. Its the kingston kth-xw8200/1gb.  http://cgi.ebay.com/Kingston-KTH-XW8200-1G-1GB-400​MHz-DDR2-400-PC2-3200-/2506531301

  • Time Machine restore left disk info on icons

    The other day I had to use Time Machine to restore my system back a couple of days. Everything seemed to work fine, but afterwards all my disk icons on the desktop have fonts under them showing disk size and remaining free space. This doesn't seem to