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.

Similar Messages

  • Why not to use static methods in interfaces?

    why?

    Because static methods are always attached to a particular class -- not an object. So object polymorphism (which is what interfaces are good for) won't help. Now, what you can do is say that subclasses must implement a method that looks an awful lot like a static method, in that it doesn't depend on object state.
    This bugged me, and it still bugs me a little bit in that I have to instantiate an object of a type in order to call these pseudo-static methods. When the pseudo-static methods tell the user how to initialize the object, you get a bit of a chicken-and-egg problem.

  • Why there should not be many static methods.

    Why a java class should not have many static methods.How is memory managed in case of static methods.
    If a Utility class has static methods then we can use methods directly by class name but if we do not make the methods static then we can acess methods using object.How does it make the difference.I know that there remains a single copy of class variables/methods.But i want to know how class memory is managed and garbage collected.

    shobhit123 wrote:
    Why a java class should not have many static methods.How is memory managed in case of static methods.
    If a Utility class has static methods then we can use methods directly by class name but if we do not make the methods static then we can acess methods using object.How does it make the difference.I know that there remains a single copy of class variables/methods.But i want to know how class memory is managed and garbage collected.The reason to discourage static methods is stylistic rather than technical. It encourages object oriented thinking.
    Each loaded class is represented by a Class object, and associated with that it a block of memory for static fields. As with all such storage this block is, as viewed from code, rather like an array with one, or in the case of double or long values, two slots per field.
    Because the class loader maintains a map from FQN to Class this storage is only released if the class loader that loaded it becomes unreachable, which happens only in situations like the un-deployment of a web application or EJB.
    Local variables for static methods are allocated in a stack frame, just as with instance methods. There's really no significant difference there.

  • IOS Cangjie input method can not be used. Original with Space Bar word selection function is invalid, as soon as possible to solve, it will affect the most users in Taiwan and Hong Kong.

    iOS Cangjie input method can not be used. Original with Space Bar word selection function is invalid, as soon as possible to solve, it will affect the most users in Taiwan and Hong Kong.

    No PR1.2 Firmware update, No update for Nokia Messaging, No updates for Ovi Maps .... Why is the N900 the forgotten stepchild ?
    "PR1.2 is still being tested - http://twitter.com/luovanto/statuses/13087245356"
    Hong Kong Launch http://www.youtube.com/watch?v=pY8zCBzvQLo

  • How to use getAncestor(n),getdescendant(child,child) in sql why they are use please give me example

    how to use getAncestor(n),getdescendant(child,child) in sql why they are use please give me example
    jitendra

    Below are a few examples that demonstrate these hierarchyid data type methods.  See the hierarchyid reference in the SQL Server Books Online for more examples of these and other methods (http://technet.microsoft.com/en-us/library/bb677193.aspx).
    --return a child of this node ('/1/')
    SELECT CAST('/' AS hierarchyid).GetDescendant(NULL, NULL).ToString();
    --returns a child of this node greater than child node '/1/' ('/2/')
    SELECT CAST('/' AS hierarchyid).GetDescendant(CAST('/1/' AS hierarchyid), NULL).ToString();
    --returns a child of this node less than chold node '/1/' ('/0/')
    SELECT CAST('/' AS hierarchyid).GetDescendant(NULL, CAST('/1/' AS hierarchyid)).ToString();
    --returns a child of this node greater than child node '/1/' and less than child node '/2/' ('/1.1/')
    SELECT CAST('/' AS hierarchyid).GetDescendant(CAST('/1/' AS hierarchyid), CAST('/2/' AS hierarchyid)).ToString();
    --return ancestor of node 1 level up from this node ('/1/2/')
    SELECT CAST('/1/2/3/' AS hierarchyid).GetAncestor(1).ToString();
    --return ancestor of node 2 levels up from this node ('/1/')
    SELECT CAST('/1/2/3/' AS hierarchyid).GetAncestor(2).ToString();
    Dan Guzman, SQL Server MVP, http://www.dbdelta.com

  • Why do we use static block ????

    my question is that why do we use static block for certain statements and declarations ?? what advantage do they hold???
    Please help me........

    Here is an example:
    If you use a JDBC-driver, it's enough to write:
       String driverName = "package.MyDriver";
       Class.forName(driverName);In the class "MyDriver" there is a static block:
    public class MyDriver implements java.sql.Driver {
       static {
          MyDriver driver = new MyDriver();
          java.sql.DriverManager.registerDriver(driver);
    }

  • Static Methods with all Final Parameters

    Gurus,
    I know the synchronization and static method question has been hashed out ad infinitum here. However, I was thinking of a slight twist. (Did a search but could not find something related to this. If this has already been posted, my apologies).
    Suppose you have a static method in which all of the parameters in the method signature are declared final. Let's assume also that you are not performing an operation with a high latency (say, database or network operations).
    Would it be "safe" to leave the static method unsynchronized in a multi-threaded environment? Would the final keyword(s) ensure that, throughout method execution, there is no longer a race condition?
    Would there be a difference between a primitive:
    static final public void doSomething(final int param) {}
    And an object that has mutator methods:
    static final public void doSomething(final List param) {}
    Basically, not having a formal CS background, I'm not sure how static methods are actually invoked on a low-level. It probably varies across JVM's, and maybe this question doesn't make much sense. However, I thought I would throw this out to see if anyone had implemented something similar.
    I might be giving "final" too much credit., but what would actually happen in a multi-threaded environment?
    Thanks much!
    - Saish
    "My karma ran over your dogma." - Anon

    I know the synchronization and static method question
    has been hashed out ad infinitum here. What question's that then?
    Suppose you have a static method in which all of the
    parameters in the method signature are declared final.
    Let's assume also that you are not performing an
    operation with a high latency (say, database or
    network operations).
    Would it be "safe" to leave the static method
    unsynchronized in a multi-threaded environment?Whether or not the parameters are final makes no difference - method parameters are local to the method and so are only visible to the current thread anyway. So making them final will have no effect on anything goning on in any other thread.
    Whether or not you are performing operations has no effect on whether or not you can call a method thread-safe. It might mean there is less contention and it might make race conditions less likely, but it won't eliminate them.
    So the answer is: If your would be thread safe with non-final parameters, then it will still be thread-safe when the parameters are all final. If it is not thread-safe with non-final parameters, then it will still not be thread safe with final parameters.
    Would the final keyword(s) ensure that, throughout
    t method execution, there is no longer a race
    condition?No. Absoloutely not.

  • Why cant i use air print with my hp deskjet 3050

    why cant i use air print with my hp deskjet 3050

    The HP Deskjet 3050A J611 is AirPrint compatible.
    If it is not working for you, try restarting your router as well as the printer. Power them down, wait a moment or two, then power them back up again. It should work.

  • Why do we use ejbCreate() method? what does it returns?

    why do we use ejbCreate() method? what does it returns?

    People think its easier to get answers handed tothem
    instead of looking...I do my best to disabuse them of that notion.I've given up on that idea, too much hard work.
    Instead I've just written off the entire current generation of schoolkids as useless, good only for (at most) menial labour.

  • Why do we use init() method instead of constructor to initialize a servlet?

    Why do we use init() method instead of constructor to initialize a servlet?

    I suspect the reasons are partly historical. A servlet is loaded dynamically, by class name and, once you've loaded the Class, it's easier to to a newInstance, using the default construtor than it is to search for a particular matching constructor and invoke it.

  • Why not make one of these with plexiglass instead of real glass that is easily broken when dropped

    Why not make one of these with plexiglass instead of real glass that is easily broken when dropped?

    lmm10873 wrote:
    Well I figure with the price we have to pay for these things they should be a little more sturdy. As high-tech as Apple is there has got to be something they could do to make them more durable. More than half the people I know have cracked screens guess they just don't bother to complain about them...What's the point anyway!
    This is the problem with extrapolating personal experience to generalized statements about a product that has been sold in the many millions in dozens of countries around the world.  I have several family members, many friends and most of my co-workers have been given iPhone 4's and 4s's as their work phone, and not one of those people that I know with iPhone 4/4s phones has ever had a front nor back screen break.  So from my perspective, you and your friends are the extreme few, the complete opposite of your perspective.

  • NEED HELP WITH USING STATIC METHOD - PLEASE RESPOND ASAP!

    I am trying to set a value on a class using a static method. I have defined a servlet attribute (let's call it myAttribute) on my webserver. I have a serlvet (let's call it myServlet) that has an init() method. I have modified this init() method to retrieve the attribute value (myAttribute). I need to make this attribute value accessible in another class (let's call it myOtherClass), so my question revolves around not knowing how to set this attribute value on my other class using a static method (let's call it setMyStuff()). I want to be able to make a call to the static method setMyStuff() with the value of my servlet attribute. I dont know enough about static member variables and methods. I need to know what to do in my init() method. I need to know what else I need to do in myServlet and also what all I need in the other class as well. I feel like a lot of my problems revolve around not knowing the proper syntax as well.
    Please reply soon!!! Thanks in advance.

    class a
    private static String aa = "";
    public static setVar (String var)
    aa = var;
    class b
    public void init()
    a.aa = "try";
    public static void main(String b[])
    b myB = new b ();
    b.init();
    hope this help;
    bye _drag                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Can not call a static function with-in a instance of the object.

    Another FYI.
    I wanted to keep all of the "option" input parameters values for a new object that
    i am creating in one place. I thought that the easiest way would be to use a
    static function that returns a value; one function for each option value.
    I was looking for a way to define "constants" that are not stored in
    the persistent data of the object, but could be reference each time
    the object is used.
    After creating the static functions in both the "type" and "body" components,
    I created the method that acutally receives the option input values.
    In this method I used a "case" statement. I tested the input parameter
    value, which should be one of the option values.
    I used a set of "WHEN conditions" that called the same
    static functions to get the exact same values that the user should
    pass in.
    When I try to store this new version, I get the error:
    "PLS-00587: a static method cannot be invoked on an instance value"
    It points to the first "when statifc_function()" of the case function.
    This seems weird!
    If I can call the static method from the "type object" without creating
    and instance of an object, then why can't I call it within the body
    of a method of an instance of the object type?
    This doesn't seem appropriate,
    unless this implementation of objects is trying to avoid some type
    of "recursion"?
    If there is some other reason, I can not think of it.
    Any ideas?

    Sorry for the confusion. Here is the simplest example of what
    I want to accomplish.
    The anonymous block is a testing of the object type, which definition follows.
    declare
    test audit_info;
    begin
    test := audit_info(...);
    test.testcall( audit_info.t_EMPLOYER() );
    end;
    -- * ========================================== * --
    create or replace type audit_info as object
    ( seq_key integer
    , static function t_EMPLOYER return varchar2
    , member procedure test_call(input_type varchar2)
    instantiable
    final;
    create or replace type body audit_info
    as
    ( id audit_info
    static function t_EMPLOYER return varchar2
    as
    begin
    return 'EMPLOYER';
    end;
    member procedure test_call(input_type varchar2)
    as
    begin
    CASE input_type
    WHEN t_EMPLOYER()
    select * from dual;
    WHEN ...
    end case;
    end;
    end;
    The error occurs on the "WHEN t_EMPLOYER()" line. This code is only
    an example.
    Thanks.

  • Using static methods to instantiate an object

    Hi,
    I have a class A which has a static method which instantiates it. If I were to instantiate the class A twice with it's static method within class B then you would think class B would have two instances of class A, right?
    Example:
    class A
       static int i = 0;
       public A(int _i)
           i = _i;
       public static A newA(int _i)
            return new A(_i);
    class B
        public B()
            A.newA(5);
            A.newA(3);
            System.out.println(A.i);
        public static void main(String[] args)
            B b = new B();
    }Is there really two instances of class A or just one? I think it would be the same one because if you check the int i it would be 3 and not 5. Maybe static instantiated objects have the same reference within the JVM as long as you don't reference them yourself?
    -Bruce

    It
    seems like you are the only one having trouble
    understanding the question.Well I was only trying to help. If you don't want any help, its up to you, but if that's the case then I fail to see why you bothered posting in the first place...?
    Allow me to point out the confusing points in your posts:
    you would think class B would have two
    instances of class A, right?The above makes no sense. What do you mean by one class "having" instances of another class? Perhaps you mean that class B holds two static references to instances of Class A, but in your code that is not the case. Can you explain what you mean by this?
    Is there really two instances of class
    A or just one?You have created two instances.
    >I think it would be the same one because if you
    check the int i it would be 3 and not 5.
    I fail to see what that has to do with the number of instances that have been created...?
    Maybe static instantiated objects have the
    same reference within the JVM as long as you
    don't reference them yourself????? What is a "static instantiated object"? If you mean that it was created via some call to a static method, then how is it different to creating an object inside the main method, or any other method that was called by main? (i.e. any method)
    What do you mean by "the same reference within the JVM"? The same as what?
    What happened to the first call "A.newA(5)"?
    I think it was overidden by the second call
    "A.newA(3)".As i already asked, what do you mean by this?
    If you change the line for the constructor
    in A to i = i * i you will get "9" as the
    output, if you delete the call "A.newA(3)"
    you will get "25" as the output. Yes. What part of this is cauing a problem?

  • Using static methods in JavaBeans

    Hi:
    I am creating several beans 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.

    I think you mixed up JavaBeans and Enterprise JavaBeans (EJBs) ...
    I think Sun Microsystems really named them badly ...
    They are in fact totally different things ...
    I agree with them.
    Please read the tutorials first.
    Asuka Kenji (UserID = 289)
    (Duke Dollar Hunting now ...)

Maybe you are looking for