开发者

Private variables in a class can be accessed from main in Java?

I've recently started learning Java using JDK1.6. If this is a silly ques开发者_如何学编程tion, 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


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).


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜