Private fields
After this: Make a field private in Java or by an underscore in Python, and read - and + in a class diagram.
On this page · 6 sections · 3 checks
In lesson 1, a line outside the class wrote -400 into Ana's balance, and nothing stopped it. The first step towards a guarded account is to close the field: to mark it so that only the class's own code may touch it. Java and Python do this in different ways, and the difference matters.
Who may touch a field
Every field and method of a class has a : a statement of who may use it. Two kinds are enough for this tutorial:
- : only the class's own code may use it.
- : any code that holds the object may use it.
For a guarded account, the fields are private and the methods are public. Outside code can still ask the account to do things, but only by calling its methods.
In Java: a lock
Java has a word for it. Write private in front of a field, and the compiler, the tool that checks the whole file before any of it runs, refuses every line outside the class that touches that field. Here is the account with private fields, and the bad line from lesson 1 in main. Switch the block to Java.
class BankAccount: def __init__(self, owner, balance): self._owner = owner self._balance = balance
a = BankAccount("Ana", 100)a._balance = -400print(a._balance)-400
class BankAccount { private String owner; private int balance;
BankAccount(String owner, int balance) { this.owner = owner; this.balance = balance; }}
public class Main { public static void main(String[] args) { BankAccount a = new BankAccount("Ana", 100); a.balance = -400; }}Main.java:14: error: balance has private access in BankAccount
Read the Java version in order:
private int balance;declares the field private.- The constructor is inside the class, so it may set
this.balance. That line is allowed. - Line 14 is in
main, outside the class. The compiler stops there witherror: balance has private access in BankAccount, and the program never starts.
The mistake is caught before the program runs, which is the best time to catch it.
In Python: a sign, not a lock
Python has no private word. Instead it has a habit that all Python programmers follow: a name that starts with one underscore, such as _balance, belongs to the class, and outside code should leave it alone. The underscore is a sign on the door. It is not a lock. Switch the block above back to Python: the line a._balance = -400 runs, and the program prints -400.
So in Python the guard depends on people reading the sign. In practice they mostly do: code that reaches into another class's underscore fields is usually flagged as a mistake when someone reviews it.
Python has one more trick, with two underscores. Inside a class, a name that starts with two underscores is renamed with the class name in front: in the class Box, __secret becomes _Box__secret. Outside the class, nothing is renamed. Follow this program:
class Box: def __init__(self): self.__secret = 1 self._hint = 2
b = Box()b._hint = 99print(b._hint)try: print(b.__secret)except AttributeError as e: print("AttributeError:", e)b.__secret = 5print(b.__secret, b._Box__secret)99 AttributeError: 'Box' object has no attribute '__secret' 5 1
b._hint = 99changes the field with one underscore. Nothing stops it, and the print shows99.b.__secretfrom outside looks for a field named__secret. There is none, because inside the class it was stored as_Box__secret. Python raisesAttributeError, and the program catches it and prints the message.b.__secret = 5from outside is not renamed, so it makes a new field named__secret. Now the object has two fields:__secretholds 5, and_Box__secretstill holds 1. The last line prints5 1.
Two underscores make an accident less likely, but they are still not a lock. Most Python code uses one underscore, and this tutorial does too.
In a class diagram
A class diagram, from the previous tutorial, shows visibility with one sign in front of each member: a minus for private, a plus for public. Here is the guarded account that lessons 3 and 4 will build. The field names follow your language switch.
Press Run it to build the diagram one step at a time.
- classes
- 0
- relations
- 0
Check yourself
In Java, balance is declared private int balance; inside BankAccount. A line in main writes a.balance = -400;. What happens?
Outside code writes to a field the class wants kept to itself: a._balance = -400 in Python, where the field is named with an underscore, and a.balance = -400; in Java, where the field is private. Which sentence is true?
In the class diagram of BankAccount, the fields start with - and the methods with +. Which of these can code outside the class use?
Honesty notes
- Say what visibility is, and tell private (only the class's own code) from public (any code that holds the object).
- Make a field private in Java, and say that the compiler then refuses any line outside the class that touches it.
- Mark a field with one underscore in Python, and say that this is a sign to other programmers, not a lock: outside code can still change it.
- Say what two underscores do in Python: the name is changed to _Box__secret inside the class, which makes accidents less likely but locks nothing.
- Read the minus (private) and plus (public) signs in front of the members of a class diagram.