Java learning - the static keyword static modification member (2)

/ *
Once the modification member method using static, then it became a static method. Static method does not belong to the object, it belongs to the class.

If there is no static keyword, you must first create an object before you can use it through an object.
If you have a static keyword, you do not need to create an object, you can use it directly through the class name.

Whether it is a member variable or member method. If you have a static, we recommend the use of class names called.
Static variables: Static variables class name.
Static method: class name of the static method ()

Precautions:

  1. Static can not directly access non-static.
    The reason: because the memory of them is [to] some static content, [after] some non-static content.
    "Ancestors descendants do not know, but future generations know their ancestors."
  2. Among static methods can not use this.
    The reason: this represents the current object, by means of who called, who is the current object.
    * /
public class Demo02StaticMethod {

    public static void main(String[] args) {
        MyClass obj = new MyClass(); // 首先创建对象
        // 然后才能使用没有static关键字的内容
        obj.method();

        // 对于静态方法来说,可以通过对象名进行调用,也可以直接通过类名称来调用。
        obj.methodStatic(); // 正确,不推荐,这种写法在编译之后也会被javac翻译成为“类名称.静态方法名”
        MyClass.methodStatic(); // 正确,推荐

        // 对于本来当中的静态方法,可以省略类名称
        myMethod();
        Demo02StaticMethod.myMethod(); // 完全等效
    }

    public static void myMethod() {
        System.out.println("自己的方法!");
    }

}

## MyClass class

public class MyClass {

    int num; // 成员变量
    static int numStatic; // 静态变量

    // 成员方法
    public void method() {
        System.out.println("这是一个成员方法。");
        // 成员方法可以访问成员变量
        System.out.println(num);
        // 成员方法可以访问静态变量
        System.out.println(numStatic);
    }

    // 静态方法
    public static void methodStatic() {
        System.out.println("这是一个静态方法。");
        // 静态方法可以访问静态变量
        System.out.println(numStatic);
        // 静态不能直接访问非静态【重点】
//        System.out.println(num); // 错误写法!

        // 静态方法中不能使用this关键字。
//        System.out.println(this); // 错误写法!
    }

}
Published 23 original articles · won praise 0 · Views 150

Guess you like

Origin blog.csdn.net/qq_44813352/article/details/104322168