thedongthrowaway thedongthrowaway - 17 days ago 8
Java Question

Can you access private data fields without setter methods in Java?

In the top stackoverflow answer to this question (Why are instance variables in Java are always private?), someone said if you have the following class with a private string,

class Address {
private String phone;

}


then you can't modify the private string using the following code, but I tried it and it works.

// main method
Address a = new Address();
a.phone="001-555-12345";


He said you had to use a setter method, but I did it without using one.

I think I misinterpreted his answer, but I'm not sure how. I would appreciate any insight, thanks.

Answer

Your main method must be held within your Address class for this to work, since private fields are accessable only within the class that they are declared in. Try changing your code so that the main method is located elsewhere (as is usually the case) and it will no longer work.

e.g., this works:

class Address {
    private String phone;

    public static void main(String[] args) {
        Address a = new Address();
        a.phone="001-555-12345";  // this works fine -- it's within Address
    }
}

but keep the above code and try this one:

class TestAddress {

    public static void main(String[] args) {
        Address a = new Address();
        a.phone="001-555-12345";  // won't compile since it's not within Address class
    }
}
Comments