01 / 20

Defining Classes
in Java

Learn how to create custom data types by defining classes with fields and methods: the foundation of object-oriented programming.

AP Computer Science Object-Oriented Programming

What Is a Class?

A class is a blueprint for creating objects. It defines the data an object holds and the behaviors it can perform. Think of it as a template: every object built from the same class has the same structure, but its own unique values.

Classes vs Objects

Class: Dog name age bark() fetch() BLUEPRINT myDog name = "Buddy" age = 3 yourDog name = "Max" age = 5

Why Classes Matter

Organization
Group related data and behavior together instead of scattering variables and functions
Reusability
Write a class once, create as many objects from it as you need
Modeling
Represent real-world entities like students, bank accounts, or game characters

Anatomy of a Class

public class Circle { // Fields (instance variables) private double radius ; private String color ; FIELDS // Methods public double getArea () { return Math.PI * radius * radius; } public String getColor () { return color ; } METHODS }

Understanding Fields

Fields (also called instance variables) store the data that belongs to each object. Every object gets its own copy of each field.

public class Student {
  // Fields: each Student object has its own values
  private String name;
  private int grade;
  private double gpa;
}

Understanding Methods

Methods define the behaviors of a class. They can read or modify the object's fields, perform calculations, and return results.

public class Student {
  private String name;
  private double gpa;

  // Accessor (getter): returns field value
  public String getName() {
    return name;
  }

  // Mutator (setter): modifies field value
  public void setGpa(double newGpa) {
    gpa = newGpa;
  }
}

Fields vs Local Variables

Fields Local Variables
Declared Inside class, outside methods Inside a method
Scope Entire class Only within that method
Default Value Yes (0, null, false) No: must initialize
Access Modifier Can be private, public, etc. Cannot have modifiers
Lifetime As long as the object exists Until the method ends

How to Define a Class

1
Choose a meaningful name. Use PascalCase (e.g., BankAccount, not bankaccount).
2
Declare the fields. Identify the data each object needs. Mark them private.
3
Write a constructor. Initialize the fields when an object is created.
4
Add methods. Write getters, setters, and any other behaviors the object should support.
5
Test it. Create objects and call methods to verify everything works.

Example 1: Rectangle Class

public class Rectangle {
  private double width;
  private double height;

  public Rectangle(double w, double h) {
    width = w;
    height = h;
  }

  public double getArea() {
    return width * height;
  }

  public double getPerimeter() {
    return 2 * (width + height);
  }
}

Example 2: BankAccount

public class BankAccount {
  private String owner;
  private double balance;

  public BankAccount(String owner, double initialBalance) {
    this.owner = owner;
    balance = initialBalance;
  }

  public void deposit(double amount) {
    balance += amount;
  }

  public void withdraw(double amount) {
    if (amount <= balance) {
      balance -= amount;
    }
  }

  public double getBalance() {
    return balance;
  }
}

Using the BankAccount Class

public class Main {
  public static void main(String[] args) {
    // Create an object (instance)
    BankAccount acct = new BankAccount("Alice", 500.0);

    // Call methods on the object
    acct.deposit(200.0);
    acct.withdraw(50.0);

    System.out.println(acct.getBalance());
    // Output: 650.0
  }
}

The this Keyword

When a parameter has the same name as a field, use this to refer to the field. The keyword this always means "the current object."

public class Point {
  private int x;
  private int y;

  public Point(int x, int y) {
    this.x = x; // this.x = field, x = parameter
    this.y = y;
  }
}

Common Mistakes

✕ Public Fields
Declaring fields as public instead of private breaks encapsulation and lets outside code change data without validation.
✕ Forgetting this
When parameter and field share a name, omitting this means you assign the parameter to itself, leaving the field unchanged.
✕ No Constructor
Relying on default values (0, null) instead of writing a constructor leads to objects in unexpected states.

Class Components Summary

Component Purpose Example
Field Stores data private int age;
Constructor Initializes object public Dog(String n)
Getter Returns field value public int getAge()
Setter Modifies field value public void setAge(int a)
Other Method Custom behavior public void bark()

Question 1 of 5

Which of the following correctly declares a private field of type String named title?

Question 2 of 5

What is the difference between a field and a local variable?

Question 3 of 5

After calling new Cat("Whiskers", 9), what does getName() return?

Question 4 of 5

Which method signature correctly defines a getter for a private field int score?

Question 5 of 5

Why should fields generally be declared as private rather than public?