Module 5: Classes, Objects, and Constructors
Fields and Methods
Give your classes state with fields and behavior with methods so they can model something useful.
Author
Java Learner Editorial Team
Reviewer
Technical review by Java Learner
Last reviewed
2026-04-16
Java version
Java 25 LTS
Learning goals
- Declare fields inside a class
- Write simple methods that belong to the object
- Access members using dot notation
Fields store object state: A field is a variable that belongs to an object, such as a name, price, or age.
Methods define object behavior: A method is an action the object can perform, such as start(), printInfo(), or deposit().
Dot notation connects the object to its members: phone.brand reads a field and phone.printBrand() calls a method.
Good beginner design: Give the class a small number of clear fields and one or two obvious methods first.
Runnable examples
A class can store state and print it
class Phone {
String brand;
void printBrand() {
System.out.println("Brand: " + brand);
}
}
public class Main {
public static void main(String[] args) {
Phone phone = new Phone();
phone.brand = "Pixel";
phone.printBrand();
}
}Expected output
Brand: Pixel
Methods belong to the object
class Lamp {
boolean on;
void turnOn() {
on = true;
System.out.println("Lamp is on");
}
}
public class Main {
public static void main(String[] args) {
Lamp deskLamp = new Lamp();
deskLamp.turnOn();
}
}Expected output
Lamp is on
Common mistakes
Trying to use a field or method without creating an object
Create the object first with `new`, then use dot notation on that object.
Mini exercise
Create a `Game` class with a `title` field and a `start()` method that prints a message.
Summary
- Fields store data on the object.
- Methods define behavior on the object.
- Dot notation is how you access both.
Next step
Next, use constructors so objects start with useful values instead of being filled in step by step every time.
Sources used