简体   繁体   中英

Static members of a Class

I am beginner in JAVA, I was reading this code:

class trying1{
    static int x =40;
    public static void main(String ...s){
        trying1 t = new trying1();
        x =20;
        System.out.println(x); // print 20
        t.show1();
    }

    void show1(){
        System.out.println(x); // print 20
    }

}

class trying2{
    public static void main(String ...s){
    System.out.println(trying1.x); // print 40
    }
}

Why does it print 40 in class trying2 ?

I know that static data members get memory only once and everyone shares that memory. As in Class trying1 , 'x' is a class var, & if I change the value of x it will be reflected in every instance of class or you can say it value will been changed at its memory location. aAfter compiling and running class trying1 , if I run trying2.class it shows 40 as output.

However its value should have been changed to 20?

Can someone help me out in this.

Thank you!!

If you start trying2, you start another JVM. The first instance of the JVM, that was using trying1 as the main class, is stopped, and whatever trying1.main(...) did, has no effect on the second JVM.

也许是因为你从不坚持新值,而且每次 x=40

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM