Why have static methods?

What is the criterion to decide whether a method should be static or not?

lets say you have a class called Utility. No other class ever needs an instance of Utility becuase all of it's methods are static and the class is public. Example:
package com.abc.util;
/* make it final so can't extend */
public final class Utility
   /* can't call new Utility now */
   private Utility()
   /* these methods below, by just seeing their names, should be static */
   public static long ipStringtoLong(String address){}
   public static String execShellCMD(String shellCMD){}
   // ect ...
}Now a class can import and use it. There are no instances associated with these methods except the values passed to them. It makes them accessable from anywhere in your application w/o worrying about having a ref to an Object. Their accessable as long as the class can be found in your class path. Jar'em up and put them into C:\jdk1.xx\jre\lib\ext\util.jar
import com.abc.util.Utility;
// ........(String host, String port){
   long ipLong = Utility.ipStringToLong(host);

Similar Messages

  • Why is it that the interfaces cannot have static methods?

    why is it that the interfaces cannot have static methods?

    Interfaces contain polymorphic methods. Static methods are not polymorphic, and therefore would not make any sense to be in interfaces.

  • Why can't inner classes have static methods?

    I just tried to add a static method to an inner class, which would have been useful for extracting constants about said inner class, and it turns out that is not allowed.
    Of course I have other ways to code what I wanted, but I'm curious as to why this restriction was set in place. Anybody know?

    Probably because an inner class is tied to an instance of the enclosing class. I think that, conceptually at least, the inner class' definition itself only exists in the context of an instance of the enclosing class. While I'm sure it would have been technically possible to allow it, it would be confusing and not make a whole lot of sense--what is the static context for the inner class, since the class only exists in a non-static context?

  • Why not static methods in an Interface

    why can't i make static methods part of an Interface?
    for example:
    public interface Names {
        public static String[] getNames(); // <--- "static" not allowed in an Interface.
    }what i want to say is:
    every class that implements the Names interface must have a static method, getNames() , that returns a raw array of Strings.
    why won't jave let me do this with an Interface?
    Edited by: kogose on Feb 4, 2009 5:47 PM

    this is my current solution:
    public interface Symbols {
        public String[] getSymbols();
    public class ETF implements Symbols {
        public String[] getSymbols() {
            return(ETF.symbols);
        private static String[] symbols =    { "DIG", "UYM", ...... }
    public class INDEXES implements Symbols {
        public String[] getSymbols() { return(symbols); }
        private static String[] symbols = { "^DZC", "^UTIL", "^GWI", .... }
    public class NYSE implements Symbols {
        public String[] getSymbols() {
            return(NYSE.symbols);
        private static String[] symbols =  { "GDL", "GDI", .... }
    }then to get the data:
    analyzer.analyze((new ETF()).getSymbols());
    analyzer.analyze((new INDEXES()).getSymbols());
    analyzer.analyze((new NYSE()).getSymbols());
    this looks like a hack to me?
    its weird that i create an object just to invoke one method and get static data.....
    is there an elegant way?

  • Why are static methods called with null references,valid ?

    This is my code :
    package inheritance;
    public class inh6{
         public static void method(){
         System.out.println("Called");
         public static void main(String[] args){
              inh6 t4 = null;
         t4.method();
    O/P :
    CalledHere t4 is a null reference and yet we are able to call a method on it,why is null pointerexception not thrown.Why are we able to call static methods using null references ?
    t4 is null means it doesnot refer to any memeory address,hence how is method() called correctly.
    I hope i am clear. :)
    Thank you for your consideration.

    punter wrote:
    jverd wrote:
    Memory addresses have nothing to do with it. I doubt memory addresses are even mentioned once in the JLS.
    By memory address i mean the memory location the reference is pointing to.I know what you mean. But if you think it's relevant, can you show me where in the JLS it says anything about memory locations?
    >
    You can do that because a) t4's type is "reference to inh6" and b) method() is declared static, which means that you don't need an object to call it, just the class. That class comes from the compile time type of t4. The fact that t4 is null at runtime is irrelevant.
    So at compile time the type of t4 is inh6 and hence the method is called.Is it ? Had method() not been static a NullPointerException would have been thrown.Correct.
    With non-static, non-private, non-final methods, which implementation of the method gets called is determined at runtime, buy the class of the object on which it's being called. If any one of those "non"s goes away, then the method is entirely determined at compile time, and in the case of static methods, there's no instance necessary to call the method in the first place.

  • Why have getInstance methods?

    Can anyone please explain what is the purpose of a getInstance method.
    If a class is abstract and cannot be instantiated why does the class allow you to make an instance of it by using a getInstance method. I find this concept very confusing.
    Cheers

    To control instantiation. E.g. for singletons, or factories, or like this
    public class RestrictedValue {
      private RestrictedValue(int i) { // can't be called by anybody else
      static RestrictedValue getInstance(int value) {
        if (value > 0 && value < 128) {
          return new RestrictedValue(value);
        } else {
          return null;
    }Not the nicest code, but you get the idea.

  • Can I have a static method?

    I want to know whether we can have static method and static block in Ejb.
    also I want to know the use of these and when these will be invoked by the container

    Technically speaking you can have static methods or static blocks the java compiler or teh ejb deployer will not complain
    However its always a good practice to avoid having static blocks, static methods in EJB
    if you have the urge to initialise or have a startup code in your application when EJB is loaded , you can implement the code in ejbCreate()
    - I dont see any other reason where you might need static block
    if there is any other reason please explain what cirumstances drives you to have static {} static mthd()
    if it is statess session Bean avoid having even non-static member variables
    Reasons for not having non-static member variable in Stateless Session EJB is
    1. stateless EJBs are pooled so the instances are pooled after use.. so there is a chance you might get the same instance with previous assigned values
    Hope the info helps!

  • Static Methods in Rmi

    I have a static method in my class .
    Now i want to change my class to Distributed class
    So what to do with that static method ...
    I can't take in interface , so how i can call that method
    Sunil Virmani

    The pre condition of all the remote methods is that they should have been declared in the interface implementing RemoteInterface. Now its been discussed in detail in this forum already why we cannot have static methods declared in the interface therefore by nature not being polymorphic u cannot use static methods for the aforesaid purpose.

  • Forcing static method implementaion!!

    hi guys,
    I want to force the implementation of a static method in my subclasses! How can i do it?

    thnks!!
    I wanted write some classes , each take a
    different type of document (html, word, etc.,) and
    give back the text file. thts all the work they shud
    do , and i want them to have a same signature!! and
    make sure any future addition of types ( with new
    java classes) , i shud have the same signature!!That still doesn't explain why you want to have static methods. The methods shouldn't be static, and you should create an interface.
    Kaj

  • The purpose of static methods ....?

    In lay mans terms can anyone tell me WHY we have static methods ?

    In lay mans terms can anyone tell me WHY we have
    static methods ?Static methods become class level methods and are no longer confined within the objects of the class.
    Static methods typically provide information about the class as a whole, such as the number of created objects etcetera. Another use is as an object factory. Instead of doing new all over the program you have a static create method you call to get new objects of the class.

  • Benefits of static methods?

    Why use static methods is it because memory is saved because a new instance is not required for each use?

    First of all you have to know, that creating instance of object is one of most expensive operation in java execution. Second, sometimes you don't need to have any state information within object, for example you'd like to write method to add two integer numbers given as parameters. Static methods are known also as Class methods, there is only one such method for all instances of class. Static methods are very usefull and convinient ! There are more and more reasons to use static methods !

  • Interface with a static method.

    I have tried to define an interface which requires a subclass to implement a static function.
    interface Testable {
    public static TestFrame getTestFrame();
    The idea is the the Testable object must be created with the appropriate constructer arguements, defined by the TestFrame. Thus the TestFrame must be created first.
    When I have tried this, the compiler complains that static is not allowed here.
    Is there a better way to do this?

    When I have tried this, the compiler complains that
    static is not allowed here.You can not have static methods in an interface - it would make no sense since static methods are not polymorphically overridden.
    >
    Is there a better way to do this?Since you need to know the class name in order to instantiate your object anyway, can't you just put the method in the class without it being part of the interface? - If the method is only necessary for object instantiation, then it doesn't sound like it belongs in an interface anyway - clients working with the interface type won't want to use it, so you're just cluttering up the interface.

  • Problem with calling dispose() from static method

    I have one class, where I have this:
    EditorWindow.disposeWindow();and class EditorWindow, where I have static method
    protected static void disposeWindow() {
        dispose();
    }But, dispose() cant be called from static method. Is there any way to hide or close the EditorWindow window?

    kaneeec wrote:
    I dont have references of these windows, because it would be too difficult. They are created just by new Window().setVisible(true);It's not difficult:
    Window w = new Window();
    w.setVisible(true);Now you have a reference (w) to your window that you can later call dispose() on.
    w.dispose();dispose() isn't a static method, so you have no choice but to call it on a specific instance.

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • OOPs Concept ! - Why Static Methods can't be redefined in its subclass ?

    Dear Experts ,
    I had searched the SDN , but unable to find out the satisfactorily answers ..
    Can anybody let me know the reason for the following Confusion in Oops Concept
    Question 1: As we know , We can Inherit the Static Methods in the Sub Class , But we can't redefine it in the base class  or       Sub Class  ?
    Question 2 : Why can't Static Method be Abstract ?
    Question 3 : Can a Class be Abstract or Final Both, If yes, then why ?
    Thanks in Advance
    Saurabh Goel

    As per the above discussion two of your doubts have already been clarified  so I am taking only third one.
    A class cannot never be Abstract and final both coz Abstract signifies that the implementation of the class has not been defined completelyi.e. may be some methods have been defined but few methods are still missing implementation. 'Final' is used for those classes/methods which cannot be redefined  means the complete implementation of the method has been defined no one can implement further logic under the same method.
    If you are saying your method is Final then it cannot be overridden and Abstract implies that method implementation is yet to be defined which can only be implemented if that class/method is not 'Final'. So both the terms are contradictory.
    Hope it clarifies!!!
    Thanks,
    Vishesh

Maybe you are looking for

  • Issue in the table settings of the screen.

    Hi Expert, I have an issue because some users are changing the Table Settings of the screen to display the sales orders. So if somebody make a change affect to all the systems so I want to find a way in order to limit the access to this setting. Than

  • Web Photo Album 2.2 in DW CS3

    Running the extension from the Command menu I got to selecting the folder of images and just after loading the folder, or selecting and image from the list I get this error: "While executing onClick in Create Web Photo Album 2.htm,the following Javas

  • Can I route non-XML files with NW PI 7.0?

    Hello, I have NW 7.0 PI installed. I need to implement very simple scenario: 1. There are two folders Source and Target 2. Any file (non-XML, binary for example) comes to the Source folder 3. File needs to be picked up and routed without any modifica

  • HT5569 setting up ipad mini without wi fi connection

    I am trying to connect new ipad mini without a wi fi connection. I have my ipad plugged into my computer and itunes is not recognizing it. What are my options. Do not have wi fi at home.

  • Why does Verizon call me from unrecognized CA number - 949-286-3973?

    It appears that you (Verizon) are calling my cell phone from an unidentified California number - 949-286-3973. From a brief search on the Internet, this seems to be what you are doing. PLEASE STOP DOING THIS!!! I understand it to be a survey about cu