1

I'm newbie in Java, but faced with interesting problem today. My code is provided below.

class Parent { 
    public void display() 
    { 
        System.out.println(new Child().line); 
    } 

    private class Child {
        private String line = "Greating";
    }
} 
class Program 
{ 
    public static void main(String args[]) 
    { 
        Parent obj = new Parent(); 
        obj.display(); 
    } 
} 

It's also available here. Could anyone clarify why private members of nested class is accessible in outer class? I'm a C# developer and was confused having this behavior.

Adalyat Nazirov
  • 1,611
  • 2
  • 14
  • 28
  • `Child` is not a subclass of `Parent`. It's a nested class. – ernest_k Nov 14 '18 at 05:58
  • 1
    `Child` class is accessed within its scope. So no problem. – jack jay Nov 14 '18 at 05:59
  • @Kartik, thank you! It helped a bit, but it's still not clear for me. How to make nested class private members hidden? – Adalyat Nazirov Nov 14 '18 at 06:14
  • @AdelNazirov take `Child` out of `Parent` and define it as `class Child extends Parent` because I think you are looking for a sub-class, not a nested class – Kartik Nov 14 '18 at 06:16
  • @Kartik no-no, I'm using nested class, not a subclass and it's very different from what we have in C#. So I want to understand 1) the reason why private members of nested fields are accessible 2) how to make them hidden – Adalyat Nazirov Nov 14 '18 at 06:20
  • because a nested class is within the scope of the parent class – Scary Wombat Nov 14 '18 at 06:38
  • If this is a concern, your file is too big and you should break them up. In Java, you can access private members in the same source file. The assumption is while you might need to protect yourself from making a mistake between files, you don't need to protect yourself from accessing something you don't want to access in the same file. – Peter Lawrey Nov 14 '18 at 07:39

0 Answers0