简体   繁体   English

在Java中访问私有字段

[英]Accessing private field in Java

I don't understand why I can access the private int i outside of the class while it's private. 我不明白为什么我可以在课堂外访问private int i ,而它是私有的。

public class Fish {

    private int i = 1;

    public static void main(String[] args) {
        Fish k = new Fish();
        k.i = 2; // it IS possible
    }

}

Your main method is part of the Fish class isn't it? 你的主要方法是Fish类的一部分不是吗?

The following doesn't work: 以下不起作用:

public class Fish {

    private int i = 1;

}

class Reptile{
  public static void main(String[] args) {
         Fish k = new Fish();

         k.i = 2; // Compiler error.
     }
}

Access modifiers work on class level not on object level . 访问修饰符在类级别而不是在对象级别上工作

You are allowed to access ki since the code lies within the same class as in which the member i is declared. 您可以访问ki因为代码与声明成员i类在同一个类中。

The rationale is (afaik) the following: You encapsulate the data (partly) in order to ease future maintenance and refactorings. 理由是(afaik)以下内容:您(部分)封装数据以便于将来的维护和重构。 When you refactor code, you refactor classes, not objects. 当您重构代码时,您重构类,而不是对象。

Private means that only the defining class can access the variable. 私有意味着只有定义才能访问变量。

Your main method is a method of the class Fish, and so it is allowed to access the variable 您的主要方法是类Fish的方法,因此允许访问该变量

This is not outside the class. 这不是课外的。 You're in the same class. 你在同一个班级。

You're instantiating a new instance of the same class and therefore you can access the private fields of this class. 您正在实例化同一个类的新实例,因此您可以访问此类的私有字段。

如果这是SomeOtherClass中的主要方法,则同一行将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM