java - 为什么此私有静态变量能被访问呢?
高洛峰
高洛峰 2017-04-18 10:47:37
0
11
1378
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变量却报错,为何?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(11)
Peter_Zhu

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

PHPzhong

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

黄舟

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.

刘奇

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

阿神

Why doesn’t the current class work?

Ty80

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.

小葫芦

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

大家讲道理

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.

Ty80

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

伊谢尔伦

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!