aspose file tools*
The moose likes Beginning Java and the fly likes private instance variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "private instance variable" Watch "private instance variable" New topic
Author

private instance variable

Aby Krishna
Greenhorn

Joined: Jul 10, 2010
Posts: 14
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

Joined: Oct 13, 2005
Posts: 38363
    
  23
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

    Joined: Oct 27, 2005
    Posts: 19670
        
      18

    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.


    SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
    How To Ask Questions How To Answer Questions
    Gaurav Sainii
    Greenhorn

    Joined: May 18, 2009
    Posts: 24
    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.
     
     
    subject: private instance variable