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.

7
  • Child is not a subclass of Parent. It's a nested class. Commented Nov 14, 2018 at 5:58
  • 1
    Child class is accessed within its scope. So no problem. Commented Nov 14, 2018 at 5:59
  • @Kartik, thank you! It helped a bit, but it's still not clear for me. How to make nested class private members hidden? Commented Nov 14, 2018 at 6: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 Commented Nov 14, 2018 at 6: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 Commented Nov 14, 2018 at 6:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.