0

I know that if a instance variable of a class is made private then it is not accessed directly by the object.

But in the following code,something as such is happening,and the code is running fine!

How is b able to directly access length,breadth and height?

public class Box {
    private int length,breadth,height;
    Box(int a,int b,int c){
        length=a;
        breadth=b;
        height=c;
    }
    Box(Box b){
        length=b.length;            //These lines!
        breadth=b.breadth;
        height=b.height;
    }
    int volume(){
        return length*breadth*height;
    }
}

public class BoxWeight extends Box{
    public int weight;
    BoxWeight(int a,int b,int c,int d){
        super(a,b,c);
        weight=d;
    }
    BoxWeight(BoxWeight b){
        super(b);
        weight=b.weight;
    }
}
class apples
{
    public static void main(String[] args)
    {   
        BoxWeight mybox1=new BoxWeight(10,20,30,40);
        BoxWeight clone=new BoxWeight(mybox1);
        System.out.println(mybox1.volume()+"...."+mybox1.weight);
        System.out.println(clone.volume()+"...."+clone.weight);
    }
}
mehmet mecek
  • 2,615
  • 2
  • 21
  • 25
habaddu arya
  • 119
  • 1
  • 1
  • 8
  • 1
    Access level modifiers determine whether other classes can use a particular field or invoke a particular method – Than Dec 11 '15 at 10:17
  • 1
    "I know that if a instance variable of a class is made private then it is not accessed directly by the object." What do you mean by that? Your question is quite unclear (and appears to have rather more code than you need to demonstrate the problem). – Jon Skeet Dec 11 '15 at 10:18

4 Answers4

4

Because the argument is of the same type. In java an object can access private members of other objects of the same type. Thus in this case Box can access any private members of the Box class, even in different objects.

MrHug
  • 1,315
  • 10
  • 27
1

private means that the fields (or inner classes or methods) are not visible outside the class (meaning to any other type). However as b is of the same type Box, this restriction does not apply.

hotzst
  • 7,238
  • 9
  • 41
  • 64
0

Private is inaccessible for other classes; b is also of type Box, so it is in its own home!

Andrew Spencer
  • 15,164
  • 4
  • 29
  • 48
Adil
  • 4,503
  • 10
  • 46
  • 63
0

Simply, a Box object can access privates of Box inside the Box class.

mehmet mecek
  • 2,615
  • 2
  • 21
  • 25