Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 689
Mellon Avatar asked Feb 16 '23 13:02

Mellon


2 Answers

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.

like image 174
Andy Thomas Avatar answered Feb 28 '23 10:02

Andy Thomas


Because victim is an instance of Body, it can access any field of a Body isntance.

like image 42
zw324 Avatar answered Feb 28 '23 12:02

zw324