Static methods, or not...

Ok, i've got a class with around 50 or so methods in it. im going to have around a hundred of these classes going at once. my question is: should i make all the methods static, and then pass in an instance of a class to work on? would that use less memory, or be beneficial in any way? im probably completely wrong, but i wanted to check anwyays, just in case..
so, for example
public void stuff(){
x++;
turning into
public void stuff(SomeClass target){
target.x++;
}

For each method there is (generally) one and only one implementation loaded into memory. Having 10 thousand instances of a class does not create copies 10 thousand copies of the methods. No, using static methods would be a waste of your energy and probably be a rather poor design.
Chuck

Similar Messages

  • Difference between calling static method and not static method?

    Hi,
    Suppose i want to write a util method, and many class might call this method. what is better? writing the method as static method or not static method. what is the difference. what is the advantace in what case?

    writing the method as static method or not static
    method. what is the difference.The difference is the one between static and non-static. Any tutorial or the JLs will clarify the difference, no need to repeat it here.
    what is the advantace in what case?It's usually not like you have much of a choice. If you need access to an instance's attributes, you can't make it static. Otherwise, make it static.

  • Static method or not static method

    I have a simple class, ClassA, with no shared class variables, and has only one static method only:
    class ClassA {
    public static void doIO (args) {
    try {
    //very time consuming I/O task
    catach (Exceptions e) { 
    //try to resolve the problem
    This doIO method will be called simultaneously from different objects.
    My questions are:
    1) Would this static method approach cause any robustness, efficiency problem? Or, should I change the method into a non-static method, and create a new instance of ClassA every time?
    2) If there are 20 threads call ClassA.doIO(args) at the same time, would the method be executed in parallel or queued?
    Many thanks.
    java9394

    Using a static method makes this implementation as efficient as possible. Since the class has no instance variables, there is no benefit, to either making it non-static, or creating multiple instances. If you have 20 threads calling it, they will run concurrently. So, if you do not like this behavior, the method can be declared both static, and synchronized.

  • Static method are not overriden ?

    Hi,
    as I try to understand java in depth, I come back with this simple question:
    public class hiddenVar1 {
    boolean aVariable=true;
    public static void main (String [] args) {
    System.out.println("Hello");
    public class hiddenVar2 extends hiddenVar1 {
    boolean aVariable;
    public hiddenVar2() {
    aMethod();
    void aMethod() {
    aVariable = false;
    System.out.println(aVariable);
    System.out.println(super.aVariable);
    public static void main (String [] args) {
    new hiddenVar2();
    hiddenVar1.main(new String[2]);
    The result is :
    false
    true
    Hello
    Conclusion:
    the main static method of hiddenVar1 as not been overrided by the main static method in hiddenVar2.
    So inheritance does not apply for static method ?
    Any explanation ?
    Thank's.
    John

    Firstly i think there should not be two public classes in only one file it gives compile time error.
    Secondly the output is correct.
    Static methods cannot be overriden because it will get initialize when u create instance of the class so u r calling
    -- new hiddenVar2();
    so it calls the constructor in that respective method is called.
    And the second line is calling the super class so it calls the main method of that class and prints "hello"
    hiddenVar1.main(new String[2]);

  • Why global var can be initialized with a static method and not by other static global var declared after its usage

    Take this:
    class test
    static int i=j;
    static int j=10;
    this will give illegal forward reference ....
    but this will compile successfully ..
    class test
    static int i=test1();
    static test1()
    return 20;
    plz assume we have main method in both cases ..
    java would be loading all static members first and would be assigning default values .. and then will be running all the initializers from to bottom ..
    Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
    Plz help.
    Thanks
    Abhishek Roshan

    Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
    Because the implementors of Java intentionally chose to do it that way.
    There are TWO stages to the process: preparation (which occurs first) and initialization.
    See the Java Language Spec section 12.4.1 'When Initialization Occurs
    The intent is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes. The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.3.2.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.
    Note the clause beginning 'may not refer to class variables'. And the authors give the reason for that restriction in the last sentence: detect circular initializations.
    Then if you check that referenced section 8.3.2.3 you will find this
    http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.2.3
    8.3.2.3. Restrictions on the use of Fields during Initialization
    The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
      The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
      The usage is not on the left hand side of an assignment.
      The usage is via a simple name.
      C is the innermost class or interface enclosing the usage.
    When a method is used (your example 2) no circular initialization can occur because methods are not 'initialized'.

  • Why not to use static methods - with example

    Hi Everyone,
    I'd like to continue the below thread about "why not to use static methods"
    Why not to use static methods
    with a concrete example.
    In my small application I need to be able to send keystrokes. (java.awt.Robot class is used for this)
    I created the following class for these "operations" with static methods:
    public class KeyboardInput {
         private static Robot r;
         static {
              try {
                   r = new Robot();
              } catch (AWTException e) {
                   throw new RuntimeException(e + "Robot couldn't be initialized.");
         public static void wait(int millis){
              r.delay(millis);
         public static void copy() {
              r.keyPress(KeyEvent.VK_CONTROL);
              r.keyPress(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_CONTROL);
         public static void altTab() {
              r.keyPress(KeyEvent.VK_ALT);
              r.keyPress(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_ALT);
                   // more methods like  paste(), tab(), shiftTab(), rightArrow()
    }Do you thinks it is a good solution? How could it be improved? I've seen something about Singleton vs. static methods somewhere. Would it be better to use Singleton?
    Thanks for any comments in advance,
    lemonboston

    maheshguruswamy wrote:
    lemonboston wrote:
    maheshguruswamy wrote:
    I think a singleton might be a better approach for you. Just kill the public constructor and provide a getInstance method to provide lazy initialization.Thanks maheshguruswamy for advising on the steps to create a singleton from this class.
    Could you maybe advise also about why do you say that it would be better to use singleton? What's behind it? Thanks!In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. So a singleton should be enough.But that doesn't answer why he should prefer a singleton instead over a bunch of static methods. Functionally the two are almost identical. In both cases there's only one "thing" on which to call methods--either a single instance of the class, or the class itself.
    To answer the question, the main reason to use a Singleton over a classful of static methods is the same reason the drives a lot of non-static vs. static decisions: Polymorphism.
    If you use a Singleton (and and interface), you can do something like this:
    KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();And then whatever is calling KBI's public methods only has to know that it has an implementor of that interface, without caring which concrete class it is, and you can substitute whatever implementation is appropriate in a given context. If you don't need to do that, then the static method approach is probably sufficient.
    There are other reasons that may suggest a Singleton--serialization, persistence, use as a JavaBean pop to mind--but they're less common and less compelling in my experience.
    And finally, if this thing maintains any state between method calls, although you can handle that with static member variables, it's more in keeping with the OO paradigm to make them non-static fields of an instance of that class.

  • How to determine the Class of a static methods class?

    hi,
    is there a way to get the code below to output
    foo() called on One.class
    foo() called on Two.classthanks,
    asjf
    public class Two extends One {
       public static void main(String [] arg) {
          One.foo(); // should say "foo() called on One.class"
          Two.foo(); // should say "foo() called on Two.class"
    class One {
       public static final void foo() {
          System.out.println("foo() called on "/*+something.getClass()*/);
    }

    - One.class won't resolve to Two.class when the static
    method is called via the class TwoThat's because static methods are not polymorphic. They cannot be overridden. For example try this:
    public class Two extends One {
       public static void main(String [] arg) {
          One.foo(); // should say "foo() called on One.class"
          Two.foo(); // should say "foo() called on Two.class"
          One one = new Two();
          one.foo();
          ((Two) one).foo();
       public static void foo() {
          System.out.println("foo() called on Two");
    class One {
       public static void foo() {
          System.out.println("foo() called on One");
    }

  • Find the Class Name in a static method

    Hi All,
    I am trying to find the class name inside the static main method. I want to write one main method that loads an instance of the class. Other folks have suggested tricks with the security manager or creating an Exception to look at the stack trace, but these methods don�t reflect the inheritance. I want SUBCLASSES to be able to run from the command line using the inherited main method.
    public static void main(String args[]){
          JPanel thisJPanel = (JPanel) Class.forName(????).newInstance();
    }Any Ideas

    I want
    SUBCLASSES to be able to run from the command line
    using the inherited main method.Someone pointed this out already but more directly, static methods are not inherited.
    The behavior you desire ca be achieved using the Factory pattern.
    The idea of being able to subclass an application is a little bizarre. Why don't you just do something like this:
    public static void main(String[] args){
        // check that there is at least one parameter 
        JPanel thisJPanel = (JPanel) Class.forName(args[0]).newInstance();
    }

  • Non-static method getContentPane() cannot be referenced from a static conte

    From this line I'm getting an error
    Container bmC = getContentPane();
    - non-static method getContentPane() cannot be referenced from a static context
    Aprecciate solution,
    thx

    The reason this is happening is that you can't call non-static methods from a static method. Non-static methods need an instance in order to be called. Static methods are not associated with an instance.

  • JUNIT : how to call static methods through mock objects.

    Hi,
    I am writing unit test cases for an action class. The method which i want to test calls one static method of a helper class. Though I create mock of that helper class, but I am not able to call the static methods through the mock object as the methods are static. So the control of my test case goes to that static method and again that static method calls two or more different static methods. So by this I am testing the entire flow instead of testing the unit of code of the action class. So it can't be called as unit test ?
    Can any one suggest me that how can I call static methods through mock objects.

    The OP's problem is that the object under test calls a static method of a helper class, for which he wants to provide a mock class
    Hence, he must break the code under test to call the mock class instead of the regular helper class (because static methods are not polymorphic)
    that wouldn't have happened if this helper class had been coded to interfaces rather than static methods
    instead of :
    public class Helper() {
        public static void getSomeHelp();
    public class MockHelper() {
        public static void getSomeHelp();
    }do :
    public class ClassUnderTest {
        private Helper helper;
        public void methodUnderTest() {  // unchanged
            helper.getSomeHelp();
    public interface Helper {
        public void getSomeHelp();
    public class HelperImpl implements Helper {
        public void getSomeHelp() {
            // actual implementation
    public class MockHelper implements Helper {
        public void getSomeHelp() {
            // mock implementation
    }

  • Help with JSP / Static methods in beans...

    Hi:
    I am creating several javabeans as part of my application. Is it ok, to make all of them static (no global variables are used) and access in JSP's and Servlets as XXBean.method(var1, var 1). Is this a problem ? (vs creating a new XXBean and using it in every page/servlet).
    I have gut feeling that static methods are better and give better memory usage and performance - as oppose in other scenario I am creating a new Bean for every page access - could not verify. and not sure not creating (new Bean) would give any problems.
    Thanks for sharing.

    No, static methods are not what you want. Just set the "scope" on your use-bean tag to "application".
    <jsp:useBean id="xbean" class="xpackage.XXBean" scope="application" />Alternatively, if what you are trying to do is a pure "function library", then create a tag lib, and add the function definitions like this:
    <function>
         <name>someMethod</name>
         <function-class>xpackage.XXBean</function-class>
         <function-signature>
         java.lang.String someMethod( java.lang.String )
         </function-signature>
    </function>There is a fairly concise description of how to do this at
    http://java.boot.by/wcd-guide/ch07s04.html

  • Static methods in multi-threaded environment

    Hi,
    I am wondering what happens when several threads try to access the same static method ?
    The static method is not synchronized.
    Will this create any performance issues ?
    The actual scenario is of a J2EE server, where several Session Bean instances try to access a static method in a utility class. Will some session beans have to wait till others are being serviced ?
    thnx n regards
    s giri

    thanx for replying.
    yes. the operations are thread-safe. we do not change the state of any object.
    but we make an rmi call to another application thru this static method.
    is it ok?
    Currently, my session bean has too many private methods - each calling the other application. Due to some quality metrics (a class must be restricted to 700 lines) we have to consider moving these private methods into some Helper class in the form of "public static methods". We have made many utility methods as static, but have some reservations abt doing a similar thing for these methods that call other application.
    regards
    Shivraman

  • Static Methods, the case of HashMap

        static int hash(Object x) {
            int h = x.hashCode();
            h += ~(h << 9);
            h ^=  (h >>> 14);
            h +=  (h << 4);
            h ^=  (h >>> 10);
            return h;I was cruising the HashMap class. And I noticed right away that all non interface methods were static package methods. Now isn't that bad OOP practice? Right. It breaks the inheritance relationship.
    It means I cannot make a subclass of HashMap and re-write that hash function. Was that intentional?
    on a OOP perspective or
    on a down to earth matter,
    Are static method more performant in speed? Or memory ( i guess yes here)? or what?

    I was cruising the HashMap class. And I noticed right
    away that all non interface methods were static
    package methods. Now isn't that bad OOP practice?
    Right. It breaks the inheritance relationship.
    It means I cannot make a subclass of HashMap and
    re-write that hash function. Was that intentional?If they are package-private, I take it for granted they didn't want application developers to redefine these methods.
    If they are static, they are also preventing themselves (Javasoft) to override them in subclasses that would be included in the JDK.
    I'd say in both cases, that it is intentional, since, at least in the case of the hash function, the intent is to disperse hash results even for low-dispersing custom hash functions, as was explained in another thread in ALT (wasn't it you already? ;-).
    This is maybe questionable, but defendable, that they didn't want any subclass to mess with these "optimizations".
    You can regard this as poor OO practice, but this is no more hampering you that if they had declared the method as private.
    I acknowledge that declaring the method private has the advantage of making explicit that they don't want anyone to override it.
    But by declaring it static package, they ensure no-one can override it, so the other methods in HashMap relying on this method are guaranteed that no subclass can mess with it, but other classes in the same package (say, WeakHashMap, HashSet,...), can call it. all the same
    Are static method more performant in speed? Or memory
    ( i guess yes here)? or what?Static methods are not faster in themselves, but invoking them may be, since they can be "statically" resolved.
    When the calling class is loaded in memory, the callee is loaded too, and the interpreter or JIT or HotSpot is free to inline the static method's body (no indirection).
    Even if it doesn't, invoking the static method implies to moving the program counter or pointer, or whatever, to an adress that has already been resolved once and for all (one indirection),
    whereas invoking a virtual method implies a double indirection, looking up the address in some kind of dynamic table (one per class, determined by the target object's leaf class).
    There are indeed two different bytecodes for these two situations!

  • Can Static Methods be overridden ?

    My question is can static methods be overridden ?
    I found this thread [Can Static Method be overridden ?|http://forums.sun.com/thread.jspa?threadID=644752&start=0&tstart=0] .Since it was too old,i have created this new thread.
    According to that thread discussion, Java language states that static methods cannot be overridden.
    To which kajbj posted a program which did allow overriding of static methods.To quote him :
    I filed a bug report on it. I don't know if it's expected behaviour or not, but I expect the compiler to complain if you add @Override to a static method (since it can't be overridden)
    /Kaj This is one small program code which i wrote ,which did not allow static methods to be overridden,but no error as such was displayed.
    package fundamentals;
    class SuperClass
      public static String getName()
           return "HI,CLASS...SUPER CLASS";
      public int getAge()
           return 20;
    } // END OF SUPER CLASS
    public class SubClass extends SuperClass{
    public static void main(String[] args)
              SubClass objSubClass=new SubClass();
              SuperClass objSuperClass=new SubClass();
              System.out.println(objSubClass.getName());      // SUB CLASS
              System.out.println(objSuperClass.getName());   // SUPER CLASS
              System.out.println(objSubClass.getAge());        // SUB CLASS
              System.out.println(objSuperClass.getAge());     // SUPER CLASS
                     public    static String getName()
                       return "HI,CLASS...SUB CLASS";
                     public int getAge()
                        return 40;
    } // END OF MAIN CLASSWhich gives the O/P :
    HI,CLASS...SUB CLASS
    HI,CLASS...SUPER CLASS
    40
    40So,the static method was not overridden.
    But ,why was no error message displayed ?
    Also when i modify the subclass static method,by removing the static keyword as follows :
    public  String getName()
                       return "HI,CLASS...SUB CLASS";
                     }A Error Message as :
    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
         This instance method cannot override the static method from SuperClassis displayed.
    Why this message is displayed after i remove the static keyword ?
    So can we say that Java does not allow static method to be overridden but does not display a compile/run time error when this is done ?
    Is this a bug as stated by kajbj ?
    Please let me know if i am not clear.If this question has been answered somewhere else in this forum,kindly let me know.
    Thank you for your consideration.

    amtidumpti wrote:
    My question is can static methods be overridden ?
    I found this thread [Can Static Method be overridden ?|http://forums.sun.com/thread.jspa?threadID=644752&start=0&tstart=0] .Since it was too old,i have created this new thread.
    According to that thread discussion, Java language states that static methods cannot be overridden.
    To which kajbj posted a program which did allow overriding of static methods.To quote him :
    I filed a bug report on it. I don't know if it's expected behaviour or not, but I expect the compiler to complain if you add @Override to a static method (since it can't be overridden)
    /Kaj
    Sigh! Amti, are you being misleading on purpose? Kaj did not "post a program which did allow overriding of static methods." He posted a program which used the annotation @Override on a static method, like this:
    class A {
        public static void m() {}
    class B extends A {
        @Override public static void m() {}
    }He wondered why it didn't generate an error message. Well, it does now:
    A.java:6: method does not override or implement a method from a supertype
        @Override public static void m() {}
        ^
    1 error

  • Datacorruption and static methods

    public static void myMethod( String Argument)
         int i = 0 ;
    What are the chances of data corruption in this static method?
    IF there are chances of data corruption, am I corrupt in saying that chances of data corruption for argument and Variable i are same?
    Where is function state stored in static method stored? What will happen to this if one thread pre-empts other?
    public class a
         int j;
         public static void myMethod( String Argument)
              int i = 0 ;
    How is integer j different from integer i? Where will JVM keep these variables ?

    What are the chances of data corruption in this static
    method? None. As long as this static method only acts on local variables (variables declared inside the method) each call to the method is completely separate from any other call.
    Where is function state stored in static method
    stored? What will happen to this if one thread
    pre-empts other?I'm not sure what you mean by 'function state' but static methods are not associated with an Object, though they can modify and depend on the state of static (class) varaivbles.
    How is integer j different from integer i? Where will
    JVM keep these variables ? j is a member varaible. It is associated wth the instance of the class. i is a local variable and is created at the beginning of a method call and destroyed (eventually) after the method completes.

Maybe you are looking for