The definition and use of Java_ class variable class method and the understanding of the main method

in conclusion

A class variable is to add static when defining a variable. The general format is: access modifier + static + variable name . A class method is to add static when defining a method. The general format is: access modifier + static + return type + method name .

Both class variables and class methods can be called directly with the class name. But static members can only be called in static methods, or by class names. Non-static members can be called in ordinary member methods.

Here we analyze the main method, which is a typical static method, which stores a string array of String type. The statements we defined will be stored in one by one, and then called by the jvm machine because it is static, so it is called without a new object instance. People don't talk too much and go directly to the code.

 

public class Test {
    int n = 2;
    static int m = 1;
    public static void main(String[] args) {
        int i = 9;
        System.out.println(i++);

        //good();调用不到,静态成员不能调用非静态成员
        //System.out.println(n);同上

        Test test = new Test();  //new一个Test()实例,可以调用到n
        System.out.println(test.n);

        System.out.println(Test.m);
        test.good();
        hi();//静态方法直接调用
    }
    public void good(){
        System.out.println("good()被调用");
        System.out.println(n);//普通方法可以调用静态属性
        hi();//普通方法也能调用静态方法
    }
    public static void hi(){
        System.out.println("hi()被调用");
    }
}

The result of the operation is as follows:

9
2
1
good() is called
2
hi() is called
hi() is called

Guess you like

Origin blog.csdn.net/ming2060/article/details/127799321
Recommended