Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private variables in a class can be accessed from main? [duplicate]

I've recently started learning Java. 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"?!
    }
}

This gives the output:

Account Number: 1101  
Name: Scott  
1101
like image 771
stryder Avatar asked Oct 31 '25 17:10

stryder


1 Answers

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

like image 56
developmentalinsanity Avatar answered Nov 02 '25 06:11

developmentalinsanity