declaringn a variable in java class (private,static,final)

This question already has an answer here:

  • In Java, difference between package private, public, protected, and private 26 answers

  • private means it can be accessed only by instances of class foo .

    public means it can be accessed from any object owning a reference to an instance of Class foo .

    static means it belongs to the class and thus, it's shared by all foo instances.

    final means it can't change its initial value.

    final properties can't be modified once initialized. static properties can be modified, but remember that the new value is shared by all instances. private properties can be modified only by a foo instance itself.

    This means that a static final property that: can't be modified; is shared by all instances.


    public attributes can be accessed from any class.

    private attributes can be accessed just in the class where it's declared. (This is why we need to include getters and setters for example in the other classes to retrieve private vars)

    final attributes cannot be modified and set to a different value.

    static attributes are accessed in the class itself and in its instances.


    private static final int a; // accessed only         / inside only
    private static       int b; // accessed and modified / inside only
    private        final int c; // accessed only         / inside only
    private              int d; // accessed and modified / inside only
    public  static final int e; // accessed only         / inside and outside
    public  static       int f; // accessed and modified / inside and outside
    public         final int g; // accessed only         / inside and outside
    public               int h; // accessed and modified / inside and outside
    

    As you can see:

  • static has no effect here whatsoever
  • final reduces accessed and modified to accessed only
  • private / public determines inside only / inside and outside
  • 链接地址: http://www.djcxy.com/p/24078.html

    上一篇: 您可以在VS 2013中使用Roslyn的哪些部分?

    下一篇: 在java类中声明一个变量(private,static,final)