Skip to lesson

State and behaviour: fields and methods

An object's state is the set of values in its fields right now. Its behaviour is its methods. When you call a method, it can read the state, change it, or answer a question about it.

State changes over time

A UPI wallet with Rs. 500 pays Rs. 200 and now holds Rs. 300: the same object in a new state. In a good design the state changes only through methods like pay(), which know the rules.

Example 1 · A wallet that changes its state

WalletDemo.javaJava
class Wallet {    String owner;    int balance;
    void addMoney(int amount) {        balance = balance + amount;        System.out.println("Added Rs. " + amount + ", balance Rs. " + balance);    }
    void pay(int amount) {        if (amount <= balance) {            balance = balance - amount;            System.out.println("Paid Rs. " + amount + ", balance Rs. " + balance);        } else {            System.out.println("Payment of Rs. " + amount + " declined");        }    }}
public class WalletDemo {    public static void main(String[] args) {        Wallet w = new Wallet();        w.owner = "Rohan";        w.addMoney(500);        w.pay(200);        w.pay(400);        System.out.println(w.owner + " has Rs. " + w.balance);    }}
Output
Added Rs. 500, balance Rs. 500
Paid Rs. 200, balance Rs. 300
Payment of Rs. 400 declined
Rohan has Rs. 300

What this code does

  • Each call starts from the balance the last call left behind: 0 → 500 → 300.
  • pay(400) fails the check amount <= balance, so it changes nothing. The method keeps the wallet from going negative.

Code in main only asks, w.pay(400);, and the method decides whether the payment is allowed. Here main could still write w.balance = -100; directly; Encapsulation (opens in a new tab) shows how to block that.

Methods that change fields

A bonus method should raise a student's marks for good. Write the new value into the field itself, marks = marks + bonus;: it stays in the object after the method ends, so the next call sees it.

Example 2 · Mistake: the new value goes into a local variable

BonusBugDemo.javaJava
class Student {    String name;    int marks;
    void addBonus(int bonus) {        int newMarks = marks + bonus;        System.out.println("Inside addBonus: " + newMarks);    }}
public class BonusBugDemo {    public static void main(String[] args) {        Student s = new Student();        s.name = "Diya";        s.marks = 70;        s.addBonus(5);        System.out.println(s.name + " now has " + s.marks);    }}
Output
Inside addBonus: 75
Diya now has 70

What this code does

  • newMarks is a local variable. It holds 75, but it disappears when the method ends, and the field marks never changed.
  • No error and no warning: the program simply prints the old 70.

Below is the fixed version. Step through it and watch the field keep its value between the two calls.

Trace the code

Watch the field change across two calls

class Student {
String name;
int marks;
void addBonus(int bonus) {
marks = marks + bonus;
}
}
public class BonusTrace {
public static void main(String[] args) {
Student s = new Student();
s.name = "Diya";
s.marks = 70;
s.addBonus(5);
s.addBonus(3);
System.out.println(s.name + " now has " + s.marks);
}
}

Variables

s
{name: null, marks: 0}

Output

(nothing printed yet)

Line 12new builds a Student with default fields, null and 0, and s holds its reference.

Step 1 of 8

Methods that return values

Some methods answer a question, "What is the total?", instead of changing anything. Such a method has a return type, like int or boolean, and ends with return, as in Return values (opens in a new tab).

Example 3 · Methods that return values

ResultDemo.javaJava
class Student {    String name;    int maths;    int science;
    int total() {        return maths + science;    }
    double percentage() {        return total() / 2.0;    }
    boolean hasPassed() {        return maths >= 35 && science >= 35;    }}
public class ResultDemo {    public static void main(String[] args) {        Student s = new Student();        s.name = "Kavya";        s.maths = 78;        s.science = 91;        System.out.println("Total: " + s.total());        System.out.println("Percent: " + s.percentage());        if (s.hasPassed()) {            System.out.println(s.name + " passed");        }    }}
Output
Total: 169
Percent: 84.5
Kavya passed

What this code does

  • total(), percentage() and hasPassed() only read fields and give back an answer; the state does not change.
  • if (s.hasPassed()) uses the returned boolean directly, and percentage() calls total() by its plain name on the same Kavya object.

A returned value goes back to the caller; it is not stored in a field. Use it in a print, an if or a variable, or it is lost.

Methods calling methods of the same object

A report needs the percentage and the grade, and the grade needs the percentage too. Inside an instance method, call another method of the class by its plain name, percent(); it runs on the same object.

Example 4 · A report built from small methods

ReportDemo.javaJava
class ReportCard {    String name;    int marks;    int maxMarks;
    double percent() {        return marks * 100.0 / maxMarks;    }
    char grade() {        double p = percent();        if (p >= 80) {            return 'A';        } else if (p >= 60) {            return 'B';        }        return 'C';    }
    void printReport() {        System.out.println(name + ": " + percent() + "% grade " + grade());    }}
public class ReportDemo {    public static void main(String[] args) {        ReportCard r = new ReportCard();        r.name = "Arjun";        r.marks = 390;        r.maxMarks = 500;        r.printReport();    }}
Output
Arjun: 78.0% grade B

What this code does

  • printReport() calls percent() and grade(), and grade() calls percent() again. All of them run on Arjun's object.
  • 390 * 100.0 / 500 is 78.0, which is below 80 but at least 60, so the grade is B.

Each method stays short and does one job. To change the grade rules, you edit only grade().

One method, many objects

Rohit and Gill bat with the same hit() method. Its code is written once, in the class, but every call runs on the object before the dot, so b1.hit(4) changes only Rohit's runs.

Example 5 · Two batters, separate scores

InningsDemo.javaJava
class Batter {    String name;    int runs;    int balls;
    void hit(int r) {        runs = runs + r;        balls++;    }
    void show() {        System.out.println(name + ": " + runs + " (" + balls + ")");    }}
public class InningsDemo {    public static void main(String[] args) {        Batter b1 = new Batter();        b1.name = "Rohit";        Batter b2 = new Batter();        b2.name = "Gill";
        b1.hit(4);        b2.hit(1);        b1.hit(6);        b1.hit(0);        b1.show();        b2.show();    }}
Output
Rohit: 10 (3)
Gill: 1 (1)

What this code does

  • One hit() method, two objects. Each call updates only the batter before the dot: Rohit 4 + 6 + 0 = 10 in 3 balls, Gill 1 in 1.
  • balls++ inside the method changes the field of that same batter.

Example 6 · Mistake: calling a method on the class, not an object

StaticCallDemo.javaJava
class Student {    String name;
    void show() {        System.out.println("Name: " + name);    }}
public class StaticCallDemo {    public static void main(String[] args) {        Student s = new Student();        s.name = "Priya";        Student.show();    }}
Sample compiler output
StaticCallDemo.java:13: error: non-static method show() cannot be referenced from a static context
        Student.show();
               ^
1 error

What this code does

  • show() prints one object's name, so it needs an object. Student.show() names only the class.
  • Fix: call it on the object, s.show();. The program then prints Name: Priya.

The method's code is stored once, with the class; each object stores only its own field values. That is why one method can serve any number of objects.

Find the bug

Find the method mistake

Select the line that is wrong.

This should print Name: Priya.

Round 1 of 4

Next step

Check your understanding

11 quick questions