Skip to the guide

Classes, objects and the state they own

BeginnerConcept6 pages

A class describes one kind of thing in your program, such as a bank account. An object is one account made from that description, and it holds its own data. Interviewers take these definitions for granted. What they listen for is whether each class owns its data and keeps that data's rules itself.

Metro cards and the ticket machine

Think of a city's prepaid metro cards. Every card is made from one design, and each holds its own balance. A chip inside the card is the only thing that changes that balance. Every chip runs the same small program, which pays a fare only if the balance covers it.

The ticket machine at the station looks after its own roll of tickets. It asks your card to pay and prints a ticket only if the card agrees, without reading your balance itself. A new card is sold already working, with a balance of zero or more. Ana's two cards that each hold $50 are still two cards.

In code, the card design is a class, BankAccount here, and each card is an object whose balance is its state, kept in a field. The chip's program is the class's methods, deposit and withdraw. They are the only code that changes the field, so the rule "never below zero" lives in them. A rule that must stay true for an object's whole life is called an invariant. The ticket machine is the Atm, with its cash as the roll. The card that is sold already working is the constructor, and Ana's two cards are two objects with the same fields.