• 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 instance variable

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have this basic question, how is the following code able to access the instance variable even though its private? (the code compiles without any errors)


Please refer to line 10 of the code above,
So specifically, the question i have is: "is static main() method allowed to access private instance variable of the class just like any other instance method?". This is confusing me a bit.

Thanks.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You have two questions there which you are confusing.
  • 1: Why can you get access to a private variable? You are in the same class.
  • 2: Why can you access an instance variable of newClassObj? Because you have created that instance inside the main() method and it is a method-local variable whose instance fields can be accessed.
  •  
    Sheriff
    Posts: 22783
    131
    Eclipse IDE Spring VI Editor Chrome Java Windows
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Private doesn't mean private to the instance; it means private to the top-level class. I specifically said top-level class, because private members of nested classes can be accessed by the enclosing class as well.
     
    Greenhorn
    Posts: 25
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    In line 10 of your code you are trying to access a private variable via instantiating an object of the same class. Though it is a private variable it is accessible anywhere in class it is defined. It is hidden from external classes but available within the same class.
    reply
      Bookmark Topic Watch Topic
    • New Topic