akshit dua akshit dua - 1 year ago 95
Java Question

Accessing private members of a class JAVA

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

Box(Box ob) {
width = ob.width;
height = ob.height;
depth = ob.depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;

I know it's a bad question but i couldn't find an answer
The code above compiles with no error.
But according to java the private members can be access in their class but in above code ob.width , ob.height , ob.depth (private members of ob) are accessed directly.

Answer Source

That's correct. The documentation says in the same class, not the same instance.

As both this and ob are of the same class Box, the access is allowed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download