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.

Similar Messages

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

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

  • Static methods in interface (Yes, once again!)

    I know there has been many questions about why static methods in interfaces are not allowed. I know it is forbidden by the JLS. But does anyone know the exact reason for this? Is it just a design issue or are there technical difficulties with allowing it?
    I can't think of any reason that it should be impossible to allow static methods in interfaces. I don't even think it would be very difficult to do. More importantly, it could probably be done without breaking existing code and existing JVMs (not too sure about the last one).
    So once again: Was the choice of not allowing static methods in interfaces a design choice or a technical choice?

    A better example of what you are suggesting is surely ...
    interface i {
        static void one();
    class a implements i {
        static void one() {
            // do something
    class b implements i {
        static void one() {
            // do something else
    }What would be the point of ever doing this?
    You cant call i.one() as the method doesn't exist without an instance of an implementing class.
    To actually ever be able to use that method you would effectively be casting an INSTANCE of a or b -> i. If you have an instance of an a or b then there is absolutely no reason for that method to be static.
    If you wanted to implement some sort of class (ie static) behaviour then class a could call its own internal static method from within the 'one' method.
    To get right to the point ... there isn't one. If it gets added to the language (and I can't see it in my wildest dreams) then Sun have lost their marbles, surely?
    Unless someone can give a good example of when it might be correct and useful to do so? I can't even see how it would be a convenience as it is completely unusable, no?

  • 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);
    }

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

  • Static methods in interfaces

    Java cognoscenti,
    Anyone know why I can't declare a method as static in an interface, but I can in an abstract class. Surely, semantically it's the same - defering the implementation of a static method, not an abstract class and an interface. By the way, I'm using JDK 1.2.2 if that makes a difference

    No, it's not the same. You are not "defering the
    implementation of a static method" because static
    methods are never polymorphic.
    Static methods cannot be abstract for this reason, and
    only abstract methods are allowed in interfaces.I didnt't know that. I thought that - because you can override static methods and you can call them onto an actual instance the method binding would be done at run-time, not at compile-time. So I was trying to prove you wrong, but you are correct !
    A short summary of what I've learnt so far:
    - interfaces cannot contain static methods
    - abstract classes cannot contain abstract static methods
    - static methods can be overriden, but they are not polymorphic; this means that the compiler decides which method to call at compile-time.
    /* output
    SuperClass.someMethod()
    SubClass.someMethod()
    SuperClass.someMethod()
    SuperClass.someMethod()
    SubClass.someMethod()
    SubClass.someMethod()
    SuperClass.someMethod()
    public class Test {
      public final static void main(String[] args) {
          // output: SuperClass.someMethod()
          new SuperClass().someMethod();
          // output: SubClass.someMethod()
          new SubClass().someMethod();
          // output: 2x SuperClass.someMethod()
          SuperClass someClass1 = new SubClass();
          someClass1.someMethod();
          showSuper(someClass1);
          // output: 2x SubClass.someMethod()
          SubClass someClass2 = new SubClass();
          someClass2.someMethod();
          showSub(someClass2);
          showSuper(someClass2); // SuperClass.someMethod()
      public final static void showSuper(SuperClass c) {
            c.someMethod();
      public final static void showSub(SubClass c) {
            c.someMethod();
    class SuperClass {
      public static void someMethod() {
        System.out.println("SuperClass.someMethod()");
    class SubClass extends SuperClass {
      public static void someMethod() {
        System.out.println("SubClass.someMethod()");

  • No static methods for Interfaces ?

    Hi,
    I was going though some documentation about the interfaces and it says that, an interface methods must not be static.
    Can someone please explain or direct me in the direction which tell me why the internet methods cannot be static.
    Thanx.
    Mel

    Defining a static method in a interface would be useless, since static methods can't be executed with dynamic binding. You'd have to know the name of the implementing class of the interface at compile time to call it, which would negate the need for an interface.
    For more details google it, that question has been asked thousands of times.

  • Static methods inside interfaces

    Why they are not allowed? Such methods would be very helpful in some cases. I speak, of course, about method declaration, not method definition.

    Ok , now I understand the problem. Thanks.
    And it's also impossible to override a staticmethod.
    Actually, it is very possible.Nope. That's hiding (or is it shadowing?), not overriding.
    The thing is, it only makes sense to have methods in an interface that can be overridden--by the JLS' definition of overriding--that is, where the particular method implementation that gets invoked is determined at runtime.
    Since static method invocatinos are compile-time bound, there's no reason for them to be in an interface--or indeed abstract at all, whether in an interface or abstract class.

  • Initializer block not called when static method called

    public class Initializer {
         Initializer(){
              System.out.println("Constructor called");
                   System.out.println("CLASS INITIALIZED");
         static void method(){
              System.out.println("Static method called");
         public static void main(String[] args) {
              Initializer.method();
    From the JLS
    A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
    T is a class and an instance of T is created.
    T is a class and a static method declared by T is invoked.
    [b]
    But when i call the static method , if the class is initialized shouldnt the initializer block be called, it is not called, why.

    Perhaps running something like this will add a little more colour?:
    public class Initializer {
        static {
            System.out.println("First static initializer");
            System.out.println("First instance initializer");
        Initializer() {
            System.out.println("Constructor");
        static {
            System.out.println("Second static initializer");
            System.out.println("Second instance initializer");
        static void staticMethod() {
            System.out.println("staticMethod");
        void instanceMethod() {
            System.out.println("instanceMethod");
        public static void main(String[] args) {
            System.out.println("main");
            staticMethod();
            new Initializer().instanceMethod();
    }

  • 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 ...)

  • GUI component services: Use static methods or query direct parent?

    Hi
    I have a large panel (covers most of the window) that contains a square grid of smaller panels. Each smaller panel contains a square grid of buttons. For instance, PnlGrid contains a few PnlGridSections and each PnlGridSection contains some BtnGrids.
    There is certain funtionality that must be available to BtnGrid objects but I am not sure if I should simply provide static methods in PnlGrid and access them from everywhere else in the code or have BtnGrid ask its direct parent (i.e. PnlGridSection) to deal with it.
    For instance, I am currently using a static method, PnlGrid.getIconCache(), to retrieve a reference to the icon cache and locate the texture I need from within a BtnGrid. Would it more correct to retrieve a pointer to the direct parent of this button (i.e. PnlGridSection) and have him return the pointer to the icon cache?
    Thanks

    Hi
    I have a large panel (covers most of the window) that contains a square grid of smaller panels. Each smaller panel contains a square grid of buttons. For instance, PnlGrid contains a few PnlGridSections and each PnlGridSection contains some BtnGrids.
    There is certain funtionality that must be available to BtnGrid objects but I am not sure if I should simply provide static methods in PnlGrid and access them from everywhere else in the code or have BtnGrid ask its direct parent (i.e. PnlGridSection) to deal with it.
    For instance, I am currently using a static method, PnlGrid.getIconCache(), to retrieve a reference to the icon cache and locate the texture I need from within a BtnGrid. Would it more correct to retrieve a pointer to the direct parent of this button (i.e. PnlGridSection) and have him return the pointer to the icon cache?
    Thanks

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Portal Runtime Error - iView not found

    Hi friends, I am working in SAP Enterprise Portal (EP6 SP9). I have made a URL iView pointing to an HTML file (residing on Portal server).I have attached this iView in the "Related Links" section of a page. Problem: When I access this iView by clicki

  • Activate User Menu in SAP logon screen

    1. Configure individual specific SAP user Enter transaction code  SM30 (Maintain Table Views) in your SAP command field and maintain USERS_SSM table. You would notice that no data maintained in this table during initial access. To maintain entries, c

  • Initialization of global/scope variables ONLY through ASSIGN?

    Is it only possible to initialize global resp. scope variables through an explicit ASSIGN? Or can I place e.g. a value="...." attribute inside the BPEL source code at the variable declaration to initialize it directly? Or even better: can I init the

  • Generic Delta issue..

    hi experts, i have created Datasource based on view which is based on EKPO and EKBE tables. i have date fields BUDAT, CPUDT  and CPUTM. I have selected CPUDT as Delta Field. select Calendar Day and Safety Interval Upper Limit as 1. I have initialized

  • [SOLVED] [dwm] Can't start dwm

    Hi! I've recently entered the world of tiling WM and started with dwm. Since I'm kinda insecure, and wanted to keep gnome as well, I've followed every single step in the wiki article and used the ~/.Xclients way, so I could start dwm from gdm (I've f