Objects: state + behavior
On This Lesson 11 topics
Lesson Overview
In the last lesson you saw why loose variables and methods stop scaling, and that object-oriented programming groups data with the methods that use it. This lesson gives you the vocabulary and the habit of mind for that grouping: every object has state (what it knows) and behavior (what it can do).
You will practice on everyday things first (a lamp, a library book), then on a bank account, and finally you will glance at how the account looks in Java. The Java syntax is a preview: you will learn it properly in the next module, so focus on the ideas.
Why this matters: when you design a backend, the first question is always "what are the things in this system, what do they know, and what do they do?" This lesson is the first answer to that question.
This lesson builds on the parallel-array bank from the previous lesson.
Learning Objectives
By the end of this lesson you will be able to:
- Define an object as something with state and behavior.
- Tell state from behavior for a given property or action.
- Name where state and behavior live in Java: fields and methods.
- Explain why two objects of the same kind have separate state.
- Explain that objects work together by calling each other's methods.
- Describe a bank account as an object, in words.
Written Explanation
Objects around you
Look at a desk lamp. You can describe it in two ways. First, what it is like at this moment: it is on or off, its brightness is medium, its bulb is warm white. Second, what you can do with it: switch it on, switch it off, dim it. The first list is the lamp's state. The second list is its behavior.
The Java tutorial makes the same point with real-world objects such as a dog (state: name, colour, hungry; behavior: barking, fetching) and a bicycle (state: current gear, current speed; behavior: changing gear, braking). Software objects are modeled on this idea.
- State is the data an object remembers about itself at a given moment. It can change over time.
- Behavior is what the object can do, usually by changing its state or by answering a question about it.
A useful test: state is a noun-like fact ("the balance is 10000"), behavior is a verb-like action ("deposit 2500").
Fields and methods
In a program, state is stored in fields: variables that belong to the object. Behavior is written as methods, which you already know from BEG-014. The difference from the static methods you wrote then is where they live: the methods now belong to the object and act on its own fields.
| Real-world idea | In Java |
|---|---|
| State | Fields (variables inside the object) |
| Behavior | Methods (inside the object) |
A method can change state (deposit changes the balance) or report state (describe prints the owner and balance). Both are behavior.
What is state and what is behavior? A decision rule
Ask two questions about any word in a description:
- Is it a value that sits there and describes the thing? That is state. (balance, owner, title, brightness)
- Is it something the thing does or has done to it? That is behavior. (deposit, borrow, switch on)
Watch for these traps:
- A calculated value such as "balance after interest" is the result of a behavior, not extra state, unless you decide to store it.
- "Is borrowed" is state (a yes/no fact). "Borrow" is behavior (the action that makes it true).
- The same real thing can have more state than your program needs. A bank account has a colour of card, but if the bank's rules never use it, you leave it out. You model only what matters for the problem.
Each object has its own state
If two objects are built the same way, each still has its own values. Ana's balance is not Omar's, even though both are accounts. Depositing into Ana's account changes Ana's balance only. This is the opposite of the parallel arrays, where the link between values was a convention: now one object holds one set of values.
Objects talk to each other
A real program has many objects, and they cooperate by calling each other's methods. A customer object asks an account object to deposit; a bank object asks one account to withdraw and another to deposit when money moves. Each call is a message of the form "object, please do this". The caller does not need to know how the balance is stored, only which method to call.
This also explains why behavior belongs with the data. The account knows its own balance, so it is the best place for the rule "you cannot withdraw more than the balance". If the rule lived somewhere else, every caller would have to remember it.
A first look at Java (preview)
The following is a preview. The next module teaches each part. Read it only to see state and behavior side by side.
class Account {
String owner; // state
int balance; // state
void deposit(int amount) { balance += amount; } // behavior
void describe() { System.out.println(owner + ": " + balance); } // behavior
}The two fields hold the state; the two methods are the behavior. Notice deposit has no parameter for the balance: it reads and changes the object's own balance.
Examples
Example 1: a desk lamp (simple)
| State (what it is like now) | Behavior (what it can do) |
|---|---|
| isOn: yes or no | switch on |
| brightness: 1 to 3 | switch off |
| color: warm or cool | change brightness |
Sentence check: "The lamp is on" is state. "Switch the lamp on" is behavior that changes that state. After switch on, the state isOn becomes yes.
If you own two lamps, each one has its own isOn. Switching one on leaves the other off. That is the idea of separate state.
Example 2: a library book (practical)
A book in a library system:
| State | Behavior |
|---|---|
| title | borrow |
| author | return |
| isBorrowed | describe itself |
Notes on the choices:
isBorrowedis state because it is a fact that stays true until something changes it.borrowis behavior and should check the state first: a book that is already borrowed cannot be borrowed again. This is a rule that lives with the data it protects.- "Late fee" is not obviously state of the book: it may belong to the loan or to the member. Deciding where such things belong is a design question, and lesson 4 gives you a method for the first guess.
- "Shelf colour" is real, but if no rule in the library system uses it, leave it out.
Example 3: a bank account, in words and in Java preview (realistic)
In words: an account has an owner and a balance (state). It can accept a deposit and describe itself (behavior). Here is the preview in use, with two lines creating the object, filling its state, and calling its behavior:
public class Preview {
public static void main(String[] args) {
Account ana = new Account();
ana.owner = "Ana";
ana.balance = 10000;
ana.deposit(2500);
ana.describe();
}
}With the Account class from the previous section, the output is:
Ana: 12500Walk through it:
new Account()creates one account object. (You will learnnewin the next module.)- The two assignments set its state.
ana.deposit(2500)asks the object to change its own balance: 10000 becomes 12500.ana.describe()asks the object to report its state.
Compare with the procedural version from the last lesson: deposit(balances, 0, 2500);. Here the caller names the object, and the object handles its balance.
Backend Insight
Backend systems are collections of objects that represent business things and cooperate: an Order that knows its items and its status, a Customer that knows their name and email, a PaymentService that charges a card. The words you used in this lesson map straight onto the code you will read: fields hold the data, methods are the operations, and requests from the outside end up as method calls on objects.
Two practical points. First, state is what gets saved: the data you store in a database is, to a large extent, the state of your objects. Second, rules that protect state belong in the behavior. If an Order knows its own status, it can refuse to be shipped before it is paid. Putting that check in one method instead of in ten callers is what keeps real systems consistent.
Common Mistakes
Mistake 1: Mixing up state and behavior
- Incorrect: "Deposit is a field of the account."
- Correct: "Deposit is a behavior (a method). The balance is state (a field)."
Quick test: if you can put a number or text in it, it is probably state; if it is an action you can ask for, it is behavior.
Mistake 2: Storing everything you can think of
An object should hold the state that matters for your problem. A student record in a grading system needs a name and grades, not their favourite food. Extra state means extra code to keep it correct.
Mistake 3: Thinking all objects of one kind share the same values
Two accounts built the same way have separate balances. Changing one does not change the other.
Mistake 4: Putting the behavior far from the data
If the rule "no withdrawal above the balance" is written in main, every other caller has to repeat it. Put the rule in the object that owns the balance.
Exercises
Try each exercise yourself before opening the solutions.
Level A: Foundation
A1. Define state and behavior in one sentence each.
Show solution A1
A1. State is the data an object remembers about itself at a moment, and it can change. Behavior is what the object can do, usually acting on its state.
A2. Sort into state or behavior: speed, accelerate, isLocked, lock, playlistName, skipSong.
Show solution A2
A2. State: speed, isLocked, playlistName. Behavior: accelerate, lock, skipSong.
A3. Where do state and behavior live in Java?
Show solution A3
A3. State in fields, behavior in methods.
Level B: Application
B1. For a traffic light, list three pieces of state and two behaviors.
Show solution B1
B1. Example: state: current colour, seconds left, whether it is blinking. Behavior: change to the next colour, start blinking. (Any reasonable answer.)
B2. For an online shop order, list four pieces of state and three behaviors. Mark one behavior that should check the state before acting.
Show solution B2
B2. Example state: order number, list of items, status, total in cents. Behavior: add item, pay, ship. ship should check that the status shows it was paid first.
B3. Two lamps, deskLamp and readingLamp, both start off. You call deskLamp.switchOn(). What is the state of readingLamp now? Why?
Show solution B3
B3. It is still off. Each object has its own state, so a call on deskLamp changes only deskLamp.
Level C: Challenge
C1. Using the preview style, write a class Lamp with a boolean field isOn and a method that switches it on, plus a main that creates one lamp, switches it on, and prints the state. Compile and run it, and write down the output. (Syntax hints: copy the shape of Account above; boolean and System.out.println you know already.)
Show solution C1
C1. Example:
public class LampDemo {
public static void main(String[] args) {
Lamp lamp = new Lamp();
lamp.switchOn();
System.out.println("On: " + lamp.isOn);
}
}
class Lamp {
boolean isOn;
void switchOn() { isOn = true; }
}Output: On: true. (A new object's fields start with default values, such as false for boolean and 0 for int; the next lesson shows this in a run.)
C2. A teammate says "the late fee is a method of the book". Argue for or against, using state and behavior. What extra information would help you decide?
Show solution C2
C2. Both sides can be argued. For: the fee is calculated from the book's due date, which is state of the book. Against: the fee also depends on the member and the library's policy, so a separate Loan object may be a better home. Useful extra information: whether the fee rate depends on who borrowed it, and whether fees are tracked per loan or per member.
Mini Challenge
Pick an object from your own life that you have not used in this lesson: a phone, a bus ticket, a recipe, a game character. Make a two-column table with at least four pieces of state and four behaviors.
Then:
- Mark one behavior that changes state, and show the state before and after (use made-up values).
- Mark one piece of state you decided to leave out, and say why it does not matter for your problem.
- Write one sentence in which two objects of your choice cooperate by one calling the other's method.
Check your work: nothing is in the wrong column, you tested each item with the verb/noun-like rule, and you gave a reason for what you left out.
Summary & Next Lesson
Key takeaways
- An object has state (what it knows) and behavior (what it can do).
- In Java, state is stored in fields and behavior is written as methods.
- Each object has its own state. Ana's balance is not Omar's.
- Objects cooperate by calling each other's methods.
- Rules that protect state belong in the behavior of the object that owns it.
- Model only the state and behavior that matter for the problem.
Next lesson
Next is "Classes as blueprints". You have seen that an Account object has an owner and a balance. The next lesson explains where those objects come from: the class is the blueprint, and each object is one thing built from it.
Self-check
- Is "withdraw" state or behavior?
- Is "isBorrowed" state or behavior?
- Where is state stored in Java?
- Ana deposits into her account. Does Omar's balance change?
- Why should the rule "no withdrawal above the balance" live in the account?
Show answers
- Behavior.
- State: it is a yes/no fact about the book.
- In fields.
- No. Each object has its own state.
- Because the account owns the balance, so one method protects it, instead of every caller having to remember the rule.
References
- Oracle, The Java Tutorials: What Is an Object?. Supports the definition of objects as bundles of state and behavior, with state in fields and behavior exposed through methods, and that objects communicate by calling methods.
- The
Accountpreview example was compiled and run with JDK 21 (javac 21.0.10); its output was copied from that run. TheLampsolution in C1 was also compiled and run. The default field values (false,0) are a Java Language Specification rule that I could not read directly on the page I fetched; the defaultsfalse,null, and0were confirmed by a JDK 21 run, shown in the next lesson.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.