简体   繁体   中英

Access private field of a instance object

I have a class, which has one field named orbits (it has the same type as my class Body and has the private modifier):

public class Body {

     // I defined it as private field
     private Body orbits = null;

     public Body getOrbits(){
         return orbits;
     }

     public void setOrbits(Body orbits){
    this.orbits = orbits;
     }

     public void capture(Body victim){
        //Why 'victim' can access 'orbits' ?
        victim.orbits = this;
     }
}

In the class, I defined a method named capture(Body victim) , which has one parameter with type Body . I am wondering in the method why I can directly access the private field orbits of instance victim ? I mean the field is private , isn't it non-accessible through the instance victim?

Privacy is not per instance - it's per class.

The class can access the private fields of all instances.

For example, the method equals( Object o ) can cast o (if appropriate) to the same type, and compare its private members with the object on which equals() was called.

因为victimBody的实例,所以它可以访问Body实体的任何字段。

According to section 6.6.1 of the Java Language Specification :

Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

由于victim的类型也Body ,的任何实例Body可以访问的私有成员victim实例。

victim is an instance of class Body and has all Attributes of that class. Every instance will have a private property orbits.

If you need a class-Attribute use "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