How and where to use Static modifier in Java?

前端 未结 7 2160
走了就别回头了
走了就别回头了 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: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
    

提交回复
热议问题