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.
Childis not a subclass ofParent. It's a nested class.Childclass is accessed within its scope. So no problem.Childout ofParentand define it asclass Child extends Parentbecause I think you are looking for a sub-class, not a nested class