为什么静态方法不能直接访问由非静态方法更改的值

roy*_*roy 5 java

public class JustPractice {

    public int points=0;

    public static void main(String args[]) {
        JustPractice ha = new JustPractice();
        ha.end();
        happy();
    }

    public void end() {
        this.points=100;
        System.out.println(points);
    }

    public static void happy() {
        JustPractice object = new JustPractice();
        System.out.println(object.points);
        return;
    }

}
Run Code Online (Sandbox Code Playgroud)

以上是显示:

100
0

而它应该显示:

100
100

Thi*_*ilo 6

您正在查看班级的两个不同实例.

每个实例都获得自己的实例字段副本,并且它们完全独立于彼此.

JustPractice ha = new JustPractice();
ha.end();    // this one has "100"

JustPractice object = new JustPractice();  // this one has "0"
System.out.println(object.points);   
Run Code Online (Sandbox Code Playgroud)

静态方法只能在访问ha实例字段时为其提供ha参数.


Ruc*_*era 2

制作points static。然后你就得到了你想要的。

public static int points=0;
Run Code Online (Sandbox Code Playgroud)

makepoints static将为类的所有实例仅保留一个变量。

否则每次初始化都会创建单独的单独变量并将值分配给0