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.

Similar Messages

  • What is the purpose of Static methods inside a class?

    Hi,
    What is the purpose of Static methods inside a class?
    I want the answers apart from "A static method does not require instance of class(to access) and it can directly be accessed by the class name itself"
    My question is what is the exact purpose of a static method ?
    Unlike attributes, a separate copy of instance attributes will be created for each instance of a class where as only one copy of static attributes will be created for all instances.
    Will a separate copy of instance method be created for each instance of a class and only one copy of static methods be create?
    Points will be rewarded for all helpful answers.

    Hi Sharma,
    Static methods is used to access statics attributes of a class. We use static attributes when we want to share the same attribute with all instances of a class, in this case if you chage this attribute through the instance A this change will change will be reflected in instance B, C........etc.
    I think that your question is correct -> a separate copy of instance method will be created for each instance of a class and only one copy of static methods be create ?
    "A static method does not require instance of class(to access) and it can directly be accessed by the class name itself"
    Static Method: call method class=>method.
    Instance Method: call method instance->method.
    Take a look at this wiki pages.
    [https://wiki.sdn.sap.com/wiki/x/o5k]
    [https://wiki.sdn.sap.com/wiki/x/ZtM]
    Best regards.
    Marcelo Ramos

  • Unsure of purpose of static methods

    Hello,
    I know the distinction between instance and class variables, but the same distinction in terms of methods is giving me a bit of confusion.
    With variables, it makes sense that common (class) variables are not copied for each instance, while instance variables are. I'm able to see the implications and purpose of separating instance and class in this case.
    I'm having trouble figuring out the purpose of instance versus class methods, though. Here, there is no 'copy' of the method to be made, right, so what are the benefits of having instance vs class methods?
    So far I know instance methods cannot be used unless an instance exists, and I think(?) the only limitation of class methods is that they be used from where their access modifier allows?
    Can anybody please shed some light on what the purpose of having both types of methods is, and maybe some other theory on it? The online tutorials I read on this matter weren't very clear for me? Thank you.

    An instance of an object has state. This Person object's state is that the name is "John Smith" and the age is 25. That other Person object's state is that the name is "Mary Jones" and the age is 17.
    If you have a canDrink() method, you have to have state--the Person's age--to use for executing that method, so you need an instance to call it on.
    john.canDrink() uses the state of that object to return true.
    mary.canDrink() uses the state of that object to return false.
    Static methods are related to the class as a whole, not to the state of any particular instance of that class.
    For example, Person.howManyPersonObjectsHaveBeenCreated()

  • How to get the class name  static method which exists in the parent class

    Hi,
    How to know the name of the class or reference to instance of the class with in the main/static method
    in the below example
    class AbstA
    public static void main(String[] args)
    System.out.println(getXXClass().getName());
    public class A extends AbstA
    public class B extends AbstA
    on compile all the class and run of
    java A
    should print A as the name
    java B
    should print B as the name
    Are there any suggestions to know the class name in the static method, which is in the parent class.
    Regards,
    Raja Nagendra Kumar

    Well, there's a hack you can use, but if you think you need it,Could you let me the hack solution for this..
    you probably have a design flaw and/or a misunderstanding about how to use Java.)May be, but my needs seems to be very genuine..of not repeat the main method contents in every inherited class..
    The need we have is this
    I have the test cases inheriting from common base class.
    When the main method of the test class is run, it is supposed to find all other test cases, which belong to same package and subpackages and create a entire suite and run the entire suite.
    In the above need of the logic we wrote in the main method could handle any class provided it knows what is the child class from which this main is called.
    I applicate your inputs on a better way to design without replicating the code..
    In my view getClass() should have been static as the instance it returns is one for all its instances of that class.
    I know there are complications the way compiler handles static vars and methods.. May be there is a need for OO principals to advance..
    Regards,
    Raja Nagendra Kumar
    Edited by: rajanag on Jul 26, 2009 6:03 PM

  • What 's the advantage of static method.

    I think if a method is declared as static, the program should allocate some spaces for the method when the program start. However, I found many static method in an erp open source project. What make me confused is that it will cost many spaces.
    Perhaps they want to lose some spaces for speed???
    Can somebody answer my question.thanks!

    > I think if a method is declared as static, the
    program should allocate some spaces for the method
    when the program start. However, I found many static
    method in an erp open source project. What make me
    confused is that it will cost many spaces.
    Perhaps they want to lose some spaces for speed???
    Can somebody answer my question.thanks!
    To be sincere, I've never thought about performance cost when static methods are used. I decide to create and use them mainly whether I have the "feeling" that it will provide me benefits, in terms of designing. Yes, it's like a feeling. I am not able to explain you why or how I have this feeling, I'm not native in English language, so choosing the appropriate words to explain my ideas sometimes is hard to me. Besides. I admit that I am a little bit lazy in this moment, I don't want to search through some dictionary...;-).
    I think the more you develop your abilities and skills in java programming, the more you can feel, you can have this "feeling", and naturally you figure out in which situations using static methods is a better choice.

  • Reg - how to find the purpose of methods in a class

    hi everyone,
               can u plz help me with how to find the purpose of methods in a class???????
    a description abt the methods in a class??????
                        thx in advance,
    regards,
    balaji.s

    Hi Balaji
    Pls find some stuff.
    reward pts if help.
    The following statements define the structure of a class:
    ·        A class contains components
    ·        Each component is assigned to a visibility section
    ·        Classes implement methods
    The following sections describe the structure of classes in more detail.
    Class Components
    The components of a class make up its contents. All components are declared in the declaration part of the class. The components define the attributes of the objects in a class. When you define the class, each component is assigned to one of the three visibility sections, which define the external interface of the class. All of the components of a class are visible within the class. All components are in the same namespace. This means that all components of the class must have names that are unique within the class.
    There are two kinds of components in a class - those that exist separately for each object in the class, and those that exist only once for the whole class, regardless of the number of instances. Instance-specific components are known as instance components. Components that are not instance-specific are called static components.
    In ABAP Objects, classes can define the following components. Since all components that you can declare in classes can also be declared in interfaces, the following descriptions apply equally to interfaces.
    Attributes
    Attributes are internal data fields within a class that can have any ABAP data type. The state of an object is determined by the contents of its attributes. One kind of attribute is the reference variable. Reference variables allow you to create and address objects. Reference variables can be defined in classes, allowing you to access objects from within a class.
    Instance Attributes
    The contents of instance attributes define the instance-specific state of an object. You declare them using the DATAstatement.
    Static Attributes
    The contents of static attributes define the state of the class that is valid for all instances of the class. Static attributes exist once for each class. You declare them using the CLASS-DATA statement. They are accessible for the entire runtime of the class.
    All of the objects in a class can access its static attributes. If you change a static attribute in an object, the change is visible in all other objects in the class.
    The technical properties of instance attributes belong to the static properties of a class. It is therefore possible to refer in a LIKE addition to the visible attributes of a class – through the class component selector or through reference variables, without prior creation of an object.
    Methods
    Methods are internal procedures in a class that define the behavior of an object. They can access all of the attributes of a class. This allows them to change the data content of an object. They also have a parameter interface, with which users can supply them with values when calling them, and receive values back from them The private attributes of a class can only be changed by methods in the same class.
    The definition and parameter interface of a method is similar to that of function modules. You define a method meth in the definition part of a class and implement it in the implementation part using the following processing block:
    METHOD meth.
    ENDMETHOD.
    You can declare local data types and objects in methods in the same way as in other ABAP procedures (subroutines and function modules). You call methods using the CALL METHOD statement.
    Instance Methods
    You declare instance methods using the METHODSstatement. They can access all of the attributes of a class, and can trigger all of the events of the class.
    Static Methods
    You declare static methods using the CLASS-METHODSstatement. They can only access static attributes and trigger static events.
    Special Methods
    As well as normal methods, which you call using CALL METHOD, there are two special methods called constructor and class_constructor that are automatically called when you create an object or when you first access the components of a class.
    reward pts if help.
    deepanker

  • Purpose of the Plugin.initApplication(InnerApplication) method

    Hi,
    Does anybody know what is the purpose of the above method? When and where shall it be called?
    As far as I know the xlet hasn't access to the plugin, so it cannot call it. There remains only a terminal.
    On other hand the terminal:
    1) if it supports the InnerApplication (ex. HTMLInnerApplication) then it doesn't need this method
    2) if it doesn't support any InnerApplication then it cannot create any instance of the InnerApplication which could be send to the above method as the parameter
    The only thing that comes to mind is to use this method in the implementation of the InnerApplicationContainer::InnerApplicationContainer(InnerApplication) constructor. But this causes other problems:
    1) the terminal doesn't know anything about the application id or other application attributes, which should be later accessible through the method XletContext.getXletProperty by this inner application
    2) the terminal doesn't know which plugin shall be used to create the xlet
    a) there is one exception if the InnerApplicationContainer::InnerApplicationContainer(InnerApplication) constructor is invoked by the delegated application, the terminal could assume that it is the same plugin which was used to create this delegated application
    b) but what if it is not a delegated application? Shall the constructor throw some exception?
    Thanks in advance,
    Adam L.

    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

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

  • What is the benefit of static in a method/function

    hello,
    can u explain the benefit of static in a function?
    and why i cannot called a function in a static method..example :
    class jalaninFungsi{
         public static void main(String args[])
              tesfungsi();
         public  void tesfungsi()
              System.out.println("ini tesfungsi");
    }its produce error : non-static method tesfungsi() cannot be referenced from static context
    thanks.

    A class is an object.
    So for example:
    class STUDENT
    public String getStudentName()
    return name;
    public int getStudentGPA()
    return GPA;
    In this case, to be able to call the function getStudentName() and getStudentGPA() you will actually need a STUDENT object.
    That means you must have declared e.g. STUDENT A; (in the main method for example), then to call those two functions above you'll need to write A.getStudentName(); and A.getStudentGPA();
    HOWEVER if you have static method, you don't need to create an object of that class type. You can just simply call the class name and then use the dot operator and call the function. e.g.:
    class STUDENT
    public static String getStudentName()
    return name;
    public static int getStudentGPA()
    return GPA;
    Notice that these are static methods, so to access these methods you just need to write STUDENT.getStudentName(); or STUDENT.getStudentGPA();
    Again, notice that here I don't use A . but instead I used the class name (STUDENT.)
    However, this is not logically correct in this (my) particular case to make those two methods static. You'll need to read more by yourself about the usage of static method. I am just trying to explain it to you why there is such thing called static methods in java.
    - o.z.

  • Confused regarding static methods

    Hello guys,
    I like to know the only purpose of static method is to call a method with out creating
    instance of that class.
    I am totaly confused why and where to use static methods.
    Thanks in advance
    aneesh

    Look at the API docs for some of the static methods in classes like java.lang.String, java.lang.Integer, java.lang.Thread, etc.
    An object--an instance of a class--has state and behavior. The state is captured in the instance variables--the array that holds the characters of a String, the name, SS#, and hireDate fields of an Employee object, etc.
    Static methods are used when the operation you're performing isn't associated with any particular instance of that class--it doesn't use or modify the state of a particular object. The operation is associated with the class as a whole.
    For instance, Integer.parseInt(String). You're not operating on an existing Integer object. Rather you're creating a new Integer from a String. It's a utility or "helper" method of the Integer class.
    And yes, do read the tutorial.

  • Namespace, static method questions

    The really useful script here is
    Sephiroth's
    Actionscript 3 PHP Unserializer. I have used the old AS2
    version many times and it's totally rad. With it you can create
    really complex data objects in php,
    serialize() them, and then
    unserialize them with this code in Flash. It dramatically reduces
    the amount of code you have to write to share complex data between
    PHP and Flash.
    The problem I'm having is that the new Actionscript 3 version
    was apparently written for Flex. When I try to use it in flash, I
    get an error:
    1004: Namespace was not found or is not a compile-time
    constant.. This error refers to this line of code:
    use namespace mx_internal;
    I know next to nothing about namespaces in Flash, but best I
    can tell, that namespace constant is apparently to be found in
    mx.core.
    At any rate, if I remove all references to mx_internal
    namespace and mx.core, I can get the script working. This brings me
    to my first questions:
    QUESTION 1: What does the use of that namespace stuff
    accomplish?
    QUESTION 2: Am I likely to suffer any unpredictable consequences
    by removing that namespace stuff?
    Also, I get an error (1061: Call to a possibly undefined
    method serialize through a reference with static type
    org.sepy.io:Serializer.) when I try to call the static methods of
    the Serialize class by instantiating it and calling the methods via
    the instance like this:
    var oSerializer:Serializer = new Serializer();
    var str = oSerializer.serialize(obj);
    That's my third question:
    QUESTION 3: Is it impossible to call a static method of a class
    from an instance of the class? Do we have to reference the class
    name instead?
    Any help would be much appreciated

    nikkj wrote:
    static methods are really class messages, that is, methods that act upon an entire classification of objects not just one instance. it is an elegant means by which to send messages to all instances or rather the class itself
    Static method calls are determined at compile time,not at run time, so it is not possible for the invocation to be polymorphic.(i.e can't be overridden)
    Because the language is defined that way - via the JLS.
    There is no technological reason that precludes a language from doing it. Smalltalk does exactly that.

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

  • What is the Purpose of getHandle() ?

    hi ... i am not cleared about the javax.ejb.EJBObject's method getHandle() .. what is it ? what is the purpose of this method . ( i know this line that it is used to get the Handle, but what is a handle ? and why it is used and how it is used ? ) and why this method is not available in javax.ejb.EJBLocalObject

    Looking up and getting reference is time consuming in case of remote calls. You could get reference of EJB using getHandle() and cache it for further calls.
    And in case of EJBLocalObject, time consuming lookup is not needed - as they are in same memory address space.
    Regards,
    Byju Joy

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

Maybe you are looking for