• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Private access in InnerClass

 
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I got suprised when this program compiles

class OuterClass {
private int outer = 10;
public static void main(String...strings)
{
new OuterClass().amethod();
}
public void amethod()
{
InnerClass h = new InnerClass();
System.out.println("Inner " + h.inner); // How it is allowed to access the private member of Inner class
}
private class InnerClass
{
private int inner = 20; // private member
public InnerClass()
{
System.out.println("Outer " + outer); // Ok to access outer
}
}
}

inner( variable) is private member. So why java is allowed to access it out side of the class InnerClass.
 
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Read this article:
http://techtracer.com/2008/04/14/mystery-of-accessibility-in-local-inner-classes/
 
Ranch Hand
Posts: 1880
Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.


Read this article for more detail:
http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
 
reply
    Bookmark Topic Watch Topic
  • New Topic