views:

155

answers:

4

I've recently started learning Java using JDK1.6. If this is a silly question, please excuse me.

If private variables can be directly accessed by objects in main() how are they 'private'?

public class Account1
{
private int accountNum;
private String name;

Account1() {
    accountNum = 1101;
    name = "Scott";
}

public void showData() {
    System.out.println("Account Number: " + accountNum +
        "\nName: " + name);
}

public static void main(String[] args) {
    Account1 myA1 = new Account1();
    myA1.showData();
    System.out.println(myA1.accountNum); //Works! What about "Private"?!
}
}

Which gives the output:

Account Number: 1101  
Name: Scott  
1101
+1  A: 

The "main" method of a given class is part of that class. Methods that are part of a class have access to private members of that class. That makes sense to me. Doesn't necessarily mean you should use it, of course.

One way to think about it is to think about one class's knowledge of another class's internal workings. My Person class shouldn't know what happens inside my Order class; it just calls public methods on it. But anything inside Person will of course know about the internal structure of Person -- even a different instance of Person.

JacobM
+5  A: 

Your main is in the Account1 class, so it's still in the same scope.

Private variables can be accessed from any code belonging to the same type. If your main method was in a separate class then it wouldn't be able to access them (without using reflection).

developmentalinsanity
Be careful - the term "local variable" could be misleading.
finnw
@finnw Good point. Adjusted to "in the same scope"
developmentalinsanity
Your second sentence is also misleading. The `main` method is not in any *instance* of `Account1`. A somewhat more correct statement would be "... private variables can be accessed by any method (or initializer) defined in the same type".
Stephen C
A: 

They are private in that they can only be accessed by that class. This means they are accessible from static methods of that class (such as main) and also from instance methods (such as showData).

One instance of the class can also access private members of another instance of the class.

If you had a separate class, say, Account2, it would not be able to access provate members of Account1.

pkaeding
A: 

This is because the main() function is a member of the class. It has access to all members of the class.

In real world code, the main function is usually situated in a "harness" class that actually bootstraps the rest of the code. This harness class is usually very lightweight and instantiates other classes that do the real work.

An Onion That is Red