Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 201 ยท Object-Oriented Programming

Fields and Instance Methods

Learn Java instance fields, their default values and initializers, instance methods that read and change object state, accessing members, and when to use fields vs local variables.

An object is data plus behavior. The data lives in instance fields: variables that belong to each object, created when the object is created and kept for as long as the object exists. The behavior lives in instance methods: methods that run on a particular object and can read and change its fields.

In Classes and Objects you created objects and set their fields from outside. That works, but it puts the knowledge about how an object should change into the code that uses it. This lesson moves that knowledge where it belongs, into the class. You'll learn how fields are initialized, what defaults they get, how instance methods find "their" object, how one object can work with another of the same class, and the important difference between a field and a local variable.

Instance fields

A field is a variable declared in the class body, outside any method. Every object gets its own copy:

Java
class Kettle {
    double liters;                    // no initializer: gets the default, 0.0
    int temperature = 20;             // field initializer: runs for every new object
    final double capacity = 1.7;      // final: set once, never changed
    List<String> log = new ArrayList<>();   // each kettle gets its OWN list
}

A field initializer (= 20, = new ArrayList<>()) runs every time an object is created, before the constructor body. That last line matters: each kettle gets a fresh list, so logging something in one kettle never shows up in another.

Default values

Unlike local variables, fields always have a value. If you don't initialize one, Java sets it to a default:

Java Default values of fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The rule is simple: numbers are zero, boolean is false, char is '\u0000', and every reference is null. The same defaults fill new arrays.

Local variables get no default. Reading one before assigning it is a compile error, variable count might not have been initialized. Java can check locals because they live inside one method; it can't track every path that touches a field, so it zeroes fields instead.

Relying on a default of 0 or false is fine when that's genuinely the right starting value (a counter, a "done" flag). Relying on null is risky: it's a NullPointerException waiting to happen. Give reference fields a real value with an initializer or a constructor.

Instance methods

An instance method is a method without static. You always call it on an object, and inside the method, the field names refer to that object's fields:

Java Methods that guard an object's state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

When kettle.pour(0.25) runs, the method doesn't receive the kettle as a visible parameter, yet it knows which kettle's liters to change. Behind the scenes, every instance method gets a hidden parameter, the object it was called on, available by the name this. Writing liters -= amount is short for this.liters -= amount. You'll use this explicitly in The this Keyword.

The kettle also shows what good methods do for an object:

  • They enforce rules. You can't pour more than the kettle holds. Every caller gets that check for free.
  • They keep related fields consistent. fill resets temperature, because new water is cold. A caller setting liters directly would forget.
  • They describe the object's state (status()) so callers don't have to assemble it from raw fields.

The refusal messages happen to print tidy numbers (1.0, 0.7), but double arithmetic is not exact: other amounts can produce values like 0.30000000000000004. That's normal floating-point behavior (see Working with Numbers); real code would format output with "%.2f", and money would use BigDecimal or whole cents.

Queries and commands

Methods tend to fall into two groups:

  • Queries (accessors) answer a question about the object and change nothing: status(), list.size(), name.length(). They return a value.
  • Commands (mutators) change the object's state: fill(), list.add(x). They usually return void, or sometimes a success flag.

Keeping the two apart makes code predictable: calling a query twice is always safe. A method named getTotal() that secretly also resets the total is a nasty surprise.

Accessing members

Inside the class, you use a field or method by its plain name. From outside, you use reference.member:

Where Field Method
Inside an instance method of the class liters (or this.liters) boil() (or this.boil())
From other code kettle.liters kettle.boil()
Inside a static method of the class only through an object: kettle.liters only through an object

The last row is the rule from Static vs Instance Methods: static code has no current object.

Working with another object of the same class

Instance methods often take another object of the same class as a parameter. Inside, you can access the other object's fields too, even private ones: access rules in Java are per class, not per object.

Java Points that work with other points

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The fields are private, so main can't touch them (uncomment the home.x = 10 line to see the error x has private access in Point). Code inside Point, however, reads other.x freely, whichever point other is. The static method at uses the same rule to fill in a new point's private fields. That's a stopgap: the normal way to create a point with starting values is a constructor, new Point(1, 2), which is the next lesson. Access Modifiers covers private and its siblings in full.

Notice that midpoint returns a new Point and leaves both inputs alone, while moveBy changes the point it's called on. Both styles are useful; just make the choice obvious from the name and the return type. (Immutable Classes explores the "always return a new object" style.)

Object state changes over time

An object's state is the current values of all its fields. Commands move an object from one state to another, so the same query can give different answers at different times:

Java A task list whose state evolves

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The fields are final, yet the lists change. final on a reference field means the field always points to the same list; the list itself can still be modified. That's usually exactly what you want for collection fields. (The final Keyword Everywhere explains the difference between a final reference and an immutable object.)

Fields vs local variables

Choosing between a field and a local variable is a design decision:

  • Use a field for information that describes the object and must survive between method calls: a kettle's water level, a list's tasks.
  • Use a local variable for temporary values needed only while one method runs: loop counters, intermediate results.

Storing temporary values in fields is a common bug. The class below keeps a running total field for a calculation that should start from zero every time. This example produces a wrong answer on purpose:

Java A field that should have been a local

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The buggy method returns 7.75 the first time and 15.5 the second, because the field remembers the previous run. Locals avoid this, and they're also safer when several threads call the same method. A good rule: make it a local unless it's part of what the object is.

When a method parameter or local has the same name as a field, the local wins inside that method; this is called shadowing, and this.name reaches the field. Variable Scope covers it, and Constructors uses it constantly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does new Counter().count print for class Counter { int count; String label; }?

    Numeric fields default to 0. Only local variables must be assigned before use; fields always get a default value.
  2. 2. In class Box { int size; void grow() { size++; } }, after Box a = new Box(); Box b = new Box(); a.grow(); a.grow(); b.grow();, what are a.size and b.size?

    Each object has its own size field, and grow() changes the field of the object it was called on.
  3. 3. A class has private int secret; and a method boolean matches(Same other) { return secret == other.secret; }. Does it compile?

    Code inside a class can access private members of any object of that class, which is what makes methods like equals and distanceTo possible.
  4. 4. What is the risk in this method? int sum; int sumOf(int[] a) { for (int x : a) sum += x; return sum; }

    The field sum survives between calls. A temporary like this should be a local variable that starts at 0 in every call.
  5. 5. A field is declared final List<String> names = new ArrayList<>();. Which statement is true?

    final means the field always refers to the same list object. The list itself is still mutable.

Summary

  • Instance fields are declared in the class body; every object has its own copy, created with the object.
  • Field initializers run for every new object; unset fields get defaults (0, 0.0, false, '\u0000', null). Local variables get no defaults.
  • Instance methods run on an object and use its fields directly; the hidden reference to that object is this.
  • Good methods enforce rules and keep related fields consistent; separate queries (return information) from commands (change state).
  • Code inside a class can access private members of any object of that class.
  • final on a reference field fixes the reference, not the object's contents.
  • Use fields for what the object is; use locals for temporary values inside one method.

Next: Constructors, where you'll make sure every object starts life in a valid state.