Home  >  Q&A  >  body text

java - 为什么此私有静态变量能被访问呢?

class Test{
    private static int i = 1;
    
    public static void main(String[] args){
        Test test = new Test();
        System.out.println(test.i);  //此处为何能访问到私有的i变量呢?
    }
}

如果与Test类不同包,调用i变量却报错,为何?

高洛峰高洛峰2744 days ago1394

reply all(11)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:49:37

    Because the main function is also a static function of the Test class

    reply
    0
  • PHPz

    PHPz2017-04-18 10:49:37

    Let me give you this picture. You can take a look, especially the difference between protected and default.

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:49:37

    The private keyword means that except for the class containing this member, other classes cannot access this member, including other classes in this package. So not only different packages, but also the same package cannot be accessed.

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:49:37

    If this doesn’t work, what is the use of privatemodified variables?

    reply
    0
  • 阿神

    阿神2017-04-18 10:49:37

    Why doesn’t the current class work?

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:49:37

    If it doesn’t work, then where is the i used? Isn’t it just declaring an i in vain?
    Also private means that i cannot be called by other classes when calling the Test class, and this class is not restricted.

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 10:49:37

    Obviously you have to re-learn: public private static protected these four common modifiers in object-oriented programming

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 10:49:37

    Since i is static, test.i (instance. static variable) is equivalent to Test.i (class. static variable), and i is private, so it can only be accessed within the Test class.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:49:37

    This is a basic programming question. I hope to take a look at the definition and scope again.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:49:37

    Because private-modified variables can be accessed in this class, this is a question about access modifiers.

    reply
    0
  • Cancelreply