0

I have a class

class Box {
    private double width;
    private double height;
    private double depth;

    Box(Box ob) {
        width = ob.width;
        height = ob.height;
        depth = ob.depth;
    }
}

this class was compiled. But i'm stack - why?! I have a private fields!

Why i have access to private fields?

Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119

3 Answers3

4

From this tutorial page:

The private modifier specifies that the member can only be accessed in its own class.

And you're accessing the field in the same class Box.

M A
  • 71,713
  • 13
  • 134
  • 174
2

Private doesn't mean only the object can access its private members, it means the class can. So in your case, any object of the Box class can access all private members of any other Box object as long as it has a reference to it.

K Mehta
  • 10,323
  • 4
  • 46
  • 76
0

Because these private field are only hidden to the outer world - that means to the outside of the class. At this class from any non static member (that is non-static method, initialization block or constructor) these are accessible directly

And for accessing these (non static) private member from a static method inside the Box class you have to create an instance of the box class and after using getter method you can access them.

public static void methodInsideBox(){
   Box b = new Box(Box b);
   //using getter method
   double width = getWidth(b);
} 
Razib
  • 10,965
  • 11
  • 53
  • 80