Static Method Call

Hi,
I had a private method which is called in a number of different places in my class. I have changed this method to be a public static method, will this effect the other areas in this class which are calling this method?
Thanks
Dude

Did you have to change any fields from instance to static? If not, then the method probably did not need to be an instance method and you should be Ok. You should just make sure that what the method is doing is not designed to update / manipulate an instance of the class.

Similar Messages

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

  • JNI static method call fails for the 6th time

    Hello,
    I have a JNI Method which calls the static method which gets reference to singleton class(getReference()), JVM crashes.
    what might be the problem?
    is it due to insufficient memory or any other reason?
    Here is my code.
    eScannerClass = gEnv->FindClass("com/elvista/jscaner/EScanner");
    eScannerContructId = gEnv->GetStaticMethodID(eScannerClass,"getReference","()Lcom/elvista/jscaner/EScanner;");
    eScannerUpdateMethodId = gEnv->GetMethodID(eScannerClass,"updateScanStatus","(Lcom/elvista/jscaner/EScanEvent;)V");
    eScannerObjectRef = gEnv->NewObject(eScannerClass,eScannerContructId);Thanx for any help on this.

    Hi,
    the eScannerContructId is refering a static method, not a constructor. Therefore you must not use gEnv->NewObject, which is only allowed for constructors. Instead you have to use gEnv->CallStaticObjectMethod to call getReference().
    Martin

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

  • Static method called from a null object reference

    Hello folks,
    Here´s the code:
    public class TestClass {
         public static void main(String[] args) {
              StaticNull _null_ = null;
              _null_.testNull();
    class StaticNull {
         public static void testNull() {
              System.out.println("testNull");
    }I know that a static method belongs to the class, so you don´t need an
    instantiated object of that class to call it. But in the code above, as
    I'm calling the testNull method from a null reference, shouldn't a NullPointerException
    be thrown?
    Best regards,
    Danniel

    sometimes wrote:
    yawmark wrote:
    Calling static methods from a reference variable should be considered a bad practice. Our coding standards prohibit it, and I suspect we're not the only ones.
    ~what are you trying to say? your coding standard encourages what tricks to invoke static methods? i mean other than using a 'reference variable'?I think you are misreading yawmark's comment. He was saying that invoking a static method using a reference variable -- as though the method weren't static:
    var.staticMethod();...is bad practice. His shop's coding standards prohibit it. And that's a common coding style standard. IDE's often warn you of that, right?
    edit: and judging by your reply #7, you and yawmark would bond over a few jars of cold beverages. You seem think with one mind.

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

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

  • JUnit : How to Mock Static Method

    Hi,
    I was using EasyMock to write Junit for the methods of the class.
    The Limitation of this library is that only Interfaces can be mocked without any much effort and behavior can be set according to our needs.
    Since, now we need to mock even normal classes, I got mocuer library from net and this too is easy to implement. The problem / limitation is that, I cant mock static methods of a class.
    Is there is any workaround / library so that even static methods can be mocked??.
    Advance thanks.

    Since you would like to mock the static method, it is not part of the class you'd like to test, I assume. The class you do want to test is supposedly under your control and contains the static invocation. I'd suggest to refactor the use of the static invocation in the class being tested.
    I see two approaches:
    1. wrap the static method call in an instance of newly created service class.
       public class ServiceMethodWrapperImpl implements ServiceMethodWrapper {
           public int serviceCall(String arg) {
             return OtherClass.staticMethod(arg);
       }and then mock the ServiceMethoWrapper interface for testing
    2. wrap the static call in a protected method of the class under test. In you test case, test a derived class in which you override the method that calls the service to use a mock:
       public class TestedClass {
         protected int callStaticMethod(String arg) {
             return OtherClass.staticMethod(arg);
         public void something() {
             // replaced OtherClass.staticMethod by
             if (callStaticMethod("Sun") == 3) {
       public void testSomethingForTheClass() {
          TestedClass instance = new TestedClass() {
               protected int callStaticMethod(String arg) {
                    return 3; // mocked answer
       }

  • Understanding Regex replace method call involving delegate

    Hello,
    I am trying to understand the $regex.replace static method call below (I came across this code snippet in the cookbook).
    $replacer = {
    param($match)
    $chars = $match.Groups[0].Value.ToCharArray()
    [Array]::Reverse($chars)
    $chars -join ''
    $regex = [Regex] "\w+"
    $regex.Replace("Hello World wide", $replacer)
    What I do not understand is the below overloaded definitions for replace method do not seem to match the above replace call. So how exactly is this working? The above call has 2 parameters passed where as none of the below overloads have less than
    3 parameters.
    PS C:\WINDOWS> [regex]::replace
    OverloadDefinitions
    static string Replace(string input, string pattern, string replacement)
    static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options)
    static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options, timespan matchTimeout)
    static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator)
    static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options)
    static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options, timespan
    matchTimeout)

    What you are looking at are the static methods ([regex]::) and their appropriate parameters which in this case have a minimum of 3 parameters to properly perform the Replace using the input, pattern and replacement
    value. If you were to use the constructor of [regex] to create a pattern like this:
    $Regex = [regex]'\w'
    You will see that the Replace method here allows for only 2 parameters because you have already satisfied the pattern when you created the Regex object.
    $Regex.Replace
    OverloadDefinitions
    string Replace(string input, string replacement)
    string Replace(string input, string replacement, int count)
    string Replace(string input, string replacement, int count, int startat)
    string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator)
    string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count)
    string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count, int startat)
    Boe Prox
    Blog |
    Twitter
    PoshWSUS |
    PoshPAIG | PoshChat |
    PoshEventUI
    PowerShell Deep Dives Book

  • 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

  • Re: No late binding for static methods

    Only the sale class has a showAdvertisement() method.
    When the compiler compiles that class it decides at compile time which exact method is called for each static method call (that's the big difference to non-static method calls: the exact method to be called is only decided at runtime in those cases).
    There's only one method showAdvertisement() and that is called in both cases in your code. Since that single method always calls the same static announcement() method, you will see the result you posted.

    JoachimSauer wrote:
    When the compiler compiles that class it decides at compile time which exact method is called for each static method call (that's the big difference to non-static method calls: the exact method to be called is only decided at runtime in those cases).I thought static methods were bound at classload-time. Demo:
    public class A {
        public static void f() {
            System.out.println("A.f");
    public class B extends A  {
        public static void f() {
            System.out.println("B.f");
    public class C  {
        public static void main(String[] args) {
            B.f();
    }If you run the above code, "A.f" is printed, as you would expect -- there is only one static method f defined.
    But if you uncomment the code in class B and recompile only it (not C!), then run C, you will get the output "B.f".
    If you run javap -c C you will see:
    public static void main(java.lang.String[]);
      Code:
       0:   invokestatic    #2; //Method B.f:()V
       3:   returnSo the byte code isn't binding the call to A.f at compile time. The choice is made at classload-time. That is why there are similar restrictions on hiding static methods as for overriding instance methods: [http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.8.3]

  • Compilation error while calling static method from another class

    Hi,
    I am new to Java Programming. I have written two class files Dummy1 and Dummy2.java in the same package Test.
    In Dummy1.java I have declared a static final variable and a static method as you can see it below.
    package Test;
    import java.io.*;
    public class Dummy1
    public static final int var1= 10;
    public static int varDisp(int var2)
    return(var1+var2);
    This is program is compiling fine.
    I have called the static method varDisp from the class Dummy2 and it is as follows
    package Test;
    import java.io.*;
    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    and when i compile Dummy2.java, there is a compilation error <identifier > expected.
    Please help me in this program.

    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    }test+=Dummy1.varDisplay(var3);
    must be in a method, it cannot just be out somewhere in the class!

  • How to call a static method from an event handler

    Hi,
       I'm trying to call a static method of class I designed.  But I don't know how to do it.  This method will be called from an event handler of a web dynpro for Abap application.
    Can somebody help me?
    Thx in advance.
    Hamza.

    To clearly specify the problem.
    I have a big part code that I use many times in my applications. So I decided to put it in a static method to reuse the code.  but my method calls functions module of HR module.  but just after the declaration ( at the first line of the call function) it thows an exception.  So I can't call my method.

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

  • Calling a method from a static method

    hello all,
    I'm calling a non-static method from a static method (from the main method). To overcome this i can make the method i am calling static but is there another way to get this to work without making the method that is being called static?
    all replies welcome, thanks

    When you call a non-static method, you are saying you are calling a method on an object. The object is an instance of the class in which the method is defined. It is a non-static method, because the instance holds data in it's instance variables that is needed to perform the method. Therefore to call this kind of method, you need to get (or create an instance of the class. Assuming the two methods are in the same class, you could do
    public class Foo
         public static void main(String[] args)
                Foo f = new Foo();
                f.callNonStaticMethod();
    }for instance.

Maybe you are looking for