0

I have a code-

public class Hello
{
    void create()
    {
        Inner obj=new Inner();
        obj.r=100; //Able to access private variable x
        obj.display(); //displays 100
    }
    class Inner
    {
        private int r=45;
        void display()
        {
            System.out.println("r is : "+r);
        }
    }
    public static void main(String[] args)
    {
        Hello ob=new Hello();
        ob.create();
    }
}

In the above code,by creating an instance of the inner class,we are able to access the private variable defined in that class.But this is not in the case of inheritance.Why it is so?For e.g.,in this code-

class One
{
    private int x;
    void getData()
    {
        x=10;
    }
    void display()
    {
        System.out.println("x is : "+x);
    }
}
class Two extends One
{
    int y;
    void putData()
    {
        One o=new One();
        o.x=13; //Error
    }
}
public class File
{
    public static void main(String[] args)
    {
        Two to=new Two();
        to.putData();
    }
}

What is the exact reason behind it?Thanks in advance...

Frosted Cupcake
  • 1,909
  • 2
  • 20
  • 42
  • 2
    possible duplicate of [In Java, what's the difference between public, default, protected, and private?](http://stackoverflow.com/questions/215497/in-java-whats-the-difference-between-public-default-protected-and-private) – Mephy Aug 29 '15 at 18:20
  • 4
    It's hard to imagine an answer other than, **because** that's how Java is implemented. – Elliott Frisch Aug 29 '15 at 18:21
  • What's wrong with using `protected`? Should work in both cases. – puelo Aug 29 '15 at 18:25
  • @Mephy-I don't think that my question is exactly the same with the question that you mentioned. – Frosted Cupcake Aug 29 '15 at 18:25
  • @puelo-Thanks for answering but I am not asking for an alternative,I am asking for the reason behind it. – Frosted Cupcake Aug 29 '15 at 18:27
  • [The spec](http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.1) and the [implementation details](http://stackoverflow.com/a/1801801/315306) – Raffaele Aug 29 '15 at 18:32
  • 2
    All members of class have access to other members of this class, even private ones. So in this case you simply think of Inner type as *member* of your outer class (although technically it isn't a member, but you get the idea). – Pshemo Aug 29 '15 at 18:36

1 Answers1

4

See 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.

Meaning that a top-level class can access the private members of it's nested classes.

Or said another way: Private means private to the top-level class and all it's nested classes, not private to the nested class itself.

Andreas
  • 154,647
  • 11
  • 152
  • 247