How and where to use Static modifier in Java?

前端 未结 7 2124
走了就别回头了
走了就别回头了 2020-11-28 10:43

How and where should we use a Static modifier for:

1. Field and
2. Method?

For example in java.lang.Math class, the fields

相关标签:
7条回答
  • 2020-11-28 11:13

    Try taking a look at this post, it also gives some examples of when to and when not to use static and final modifiers.

    Most of the posts above are similar, but this post might offer some other insight.
    When to use Static Modifiers

    0 讨论(0)
  • 2020-11-28 11:16

    Static uses less memory since it exists only once per Classloader.

    To have methods static may save some time, beacuse you do not have to create an object first so you can call a function. You can/should use static methods when they stand pretty much on their own (ie. Math.abs(X) - there really is no object the function needs.) Basically its a convenience thing (at least as far as I see it - others might and will disagree :P)

    Static fields should really be used with caution. There are quite a few patterns that need static fields... but the basics first:

    a static field exists only once. So if you have a simple class (kinda pseudocode):

    class Simple {
     static int a;
     int b;
    }
    

    and now you make objects with:

    Simple myA = new Simple();
    Simple myB = new Simple();
    myA.a = 1;
    myA.b = 2;
    myB.a = 3;
    myB.b = 4;
    System.out.println(myA.a + myA.b + myB.a + myB.b);
    

    you will get 3234 - because by setting myB.a you actually overwrite myA.a as well because a is static. It exists in one place in memory.

    You normally want to avoid this because really weird things might happen. But if you google for example for Factory Pattern you will see that there are actually quite useful uses for this behaviour.

    Hope that clears it up a little.

    0 讨论(0)
  • 2020-11-28 11:28

    You can think of a 'static' method or field as if it were declared outside the class definition. In other words

    1. There is only one 'copy' of a static field/method.
    2. Static fields/methods cannot access non-static fields/methods.

    There are several instances where you would want to make something static.

    The canonical example for a field is to make a static integer field which keeps a count across all instances (objects) of a class. Additionally, singleton objects, for example, also typically employ the static modifier.

    Similarly, static methods can be used to perform 'utility' jobs for which all the required dependencies are passed in as parameters to the method - you cannot reference the 'this' keyword inside of a static method.

    In C#, you can also have static classes which, as you might guess, contain only static members:

    public static class MyContainer
    {
        private static int _myStatic;
    
        public static void PrintMe(string someString)
        {
            Console.Out.WriteLine(someString);
            _myStatic++;
        }
    
        public static int PrintedInstances()
        {
            return _myStatic;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 11:30

    You can't instantiate an instance of java.lang.Math; there isn't a public constructor.

    Try it:

    public class MathTest
    {
        public static void main(String [] args)
        {
            Math math = new Math();
    
            System.out.println("math.sqrt(2) = " + math.sqrt(2));
        }
    }
    

    Here's what you'll get:

    C:\Documents and Settings\Michael\My Documents\MathTest.java:5: Math() has private access in java.lang.Math
            Math math = new Math();
                        ^
    1 error
    
    Tool completed with exit code 1
    
    0 讨论(0)
  • 2020-11-28 11:35

    For a field you should keep it static if you want all instances of a given class to have access to its value. For example if I have

    public static int age = 25;
    

    Then any instance of the class can get or set the value of age with all pointing to the same value. If you do make something static you run the risk of having two instances overwriting each others values and possibly causing problems.

    The reason to create static methods is mostly for utility function where all the required data for the method is passed in and you do not want to take the over head of creating an instance of the class each time you want to call the method.

    0 讨论(0)
  • 2020-11-28 11:35
    class StaticModifier
    {    
    
        {
            System.out.println("Within init block");//third
        }
        public StaticModifier()
        {
            System.out.println("Within Constructor");//fourth
        }
        public static void main(String arr[])
        {
        System.out.println("Within Main:");//second
        //StaticModifier obj=new StaticModifier();
        }
        static
        {
        System.out.print("Within static block");//first
        }
    }
    
    0 讨论(0)
提交回复
热议问题