Search code examples
javaoopencapsulation

Changing private field members without using a setter


In developing my most recent project I discovered something that breaks the encapsulation and visibility rules as i understand them.

In my GUI class I created several class variables for the textfields and buttons in my app and set them all to be private. I also set up getters for the buttons and text fields that return the values of the private members. In my SqlStatements class I reference the getters and then call setText() method on the getters and it changes the value of the private member fields. How is this possible?

For instance:

public class InitGUI {
    public static JTextField getfNameField() {     <---- getter for JTextField
        return fName;
    }

    private static JTextField fName;   <---- JTextField variable.
}

public class SqlStatements {
    // how is this able to change the value of a private member?
    InitGUI.getmNameField().setText("");
}

Solution

  • You confuse immutability with visibility. By providing getter for a private field (you break encapsulation) you expose it's methods to the outside world. (possibly some methods that changes the inner state of the fields - and your class as a consequence).