• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

private instance variable

 
Aby Krishna
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • 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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48938
60
  • Mark post as helpful
  • send pies
  • 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.
  •  
    Rob Spoor
    Sheriff
    Pie
    Posts: 20527
    54
    Chrome Eclipse IDE Java Windows
    • Mark post as helpful
    • send pies
    • 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.
     
    Gaurav Sainii
    Greenhorn
    Posts: 24
    • Mark post as helpful
    • send pies
    • 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.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic