简体   繁体   中英

shadowing static variable ( global variable)

Why in the next code I get pro.x=11?. it should be 22. Please somebody throws a light.

public class Pro {
    static int x=11;

    public static void main(String[] args)  {

    Pro pro=new Pro();
    pro.call(5);
    System.out.println(Pro.x);
    System.out.println(pro.x);  
    }
    public void call(int x){
        x=22;   
    }
}

you are not setting the static/global variable to 22, but rather the value of the argument passed. Considering it's a primitive value, call by value is used and not call by reference.

Edit: In fact as pointed out in comments, java doesn't have have call by reference, but rather call by value of a reference.

If you just wisht to change the global variable, no argument is necessary for your function, you can do it this way:

public class Pro {
    static int x=11;

    public static void main(String[] args)  {

    Pro pro=new Pro();
    pro.call();
    System.out.println(Pro.x);
    System.out.println(pro.x);  
    }
    public void call(){
        Pro.x=22;   
    }
}

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