File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

private instance variable

Aby Krishna

Joined: Jul 10, 2010
Posts: 14

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.

Campbell Ritchie

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

    Joined: Oct 27, 2005
    Posts: 20276

    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 - OCEJPAD 6
    How To Ask Questions How To Answer Questions
    Gaurav Sainii

    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.
    I agree. Here's the link:
    subject: private instance variable
    It's not a secret anymore!