简体   繁体   中英

how private static instance variable is accessed in main()

public class test
{
    private static int a;
    public static void main(string[] args)
    {
        modify(a);
        system.out.print(a);
    }
    public static void modify(int a)
    {
        a++;
    }
}

i want to know how a private static variable is accessed directly in main() method. although static variables can be accessed directly from static methods but the variable is private and method is main().. pls explain

是的,它是静态的,但是由于它与main方法位于同一类中,因此可以由该类中的静态方法(包括main)来访问...实际上,也可以由同一类中的普通方法进行访问

It doesn't bother you that modif() can access the attribute a ? Then it's the exact same thing with the main() .

The only special thing about main() is the fact that this method is used as an entry point of your application. This particularity doesn't interfer with the fact that main() is static.


By the way, your modif() method doesn't really access the static a field because it's shadowed by the parameter a .

Another thing, a++ won't do anything because you're just modifying the value of the parameter a inside a method; int is a primitive and is passed by value, so your code won't change the value of a outside of the method scope.

I think you wanted something like this :

public class test{
    private static int a;
    public static void main(string[] args){
        modify(); //<--- No parameters needed here !
        system.out.print(a);
    }

    public static void modify(){ //<--- No parameters needed here !
        a++;
    }
}

If you declare a member variable as private, this means it can only be accessed from methods in the same class. Your main() method is actually a static method in the same class, so it can access any private variables.

由于main在同一类中,因此您可以访问私有变量。

A private member variable is visible to any method of that class, static or not. There are restrictions on what static methods can do but those are separate from the visibility rules.

but public class test { private int a; public static void main(string[] args) { system.out.print(a); }

}

you can't access a instance variable 'a' directly in main()... it will show error bcoz it is private...... but how it accesses private static...

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