Classes and Objects

IB Syllabus: B3.1 – Design and implement classes, create objects, define attributes and methods.

Table of Contents

  1. Key Concepts
    1. What is a Class?
    2. What is an Object?
    3. Instantiation
    4. Attributes
    5. Methods
    6. Multiple Objects, Same Class
    7. Arrays of Objects
  2. Worked Examples
    1. Example 1: Designing a Class from Requirements
    2. Example 2: Using Objects in Main
  3. Quick Check
  4. Trace Exercise
  5. Spot the Error
  6. Predict the Output
  7. Practice Exercises
    1. Core
    2. Extension
    3. Challenge
  8. Connections

Key Concepts

What is a Class?

A class is a blueprint that defines what data (attributes) and behaviour (methods) its objects will have. The class itself is not an object – it is the template from which objects are created.

A class has three parts:

  1. Attributes (instance variables) – the data each object stores
  2. Constructor(s) – special methods that initialise a new object’s attributes
  3. Methods – operations the object can perform
public class Book {
    // 1. Attributes (instance variables)
    private String title;
    private String author;
    private int pages;

    // 2. Constructor
    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }

    // 3. Methods
    public String getTitle() {
        return title;
    }

    public String getAuthor() {
        return author;
    }

    public int getPages() {
        return pages;
    }

    public boolean isLong() {
        return pages > 300;
    }
}

By convention, class names start with an uppercase letter (Book, Student, BankAccount). Attribute and method names start with a lowercase letter (title, getTitle()). This naming convention is universal in Java.

What is an Object?

An object is a specific instance created from a class. If the class is the blueprint for a house, each house built from that blueprint is an object. Each object has its own independent copy of the attributes.

public class Main {
    public static void main(String[] args) {
        // Creating (instantiating) objects
        Book book1 = new Book("1984", "George Orwell", 328);
        Book book2 = new Book("Dune", "Frank Herbert", 412);

        // Each object has its own attribute values
        System.out.println(book1.getTitle());  // 1984
        System.out.println(book2.getTitle());  // Dune

        System.out.println(book1.isLong());    // true (328 > 300)
        System.out.println(book2.isLong());    // true (412 > 300)
    }
}

Output:

1984
Dune
true
true

book1 and book2 are two separate objects. Changing book1’s data does not affect book2 – they are independent instances of the same class.

Instantiation

Instantiation is the process of creating a new object from a class. Three things happen when you write new Book("1984", "George Orwell", 328):

  1. Memory is allocated for the new object’s attributes
  2. The constructor is called with the provided arguments
  3. A reference is returned – the variable book1 stores the memory address of the new object
Book book1 = new Book("1984", "George Orwell", 328);
//    ↑              ↑
//    reference       constructor call (creates the object)

A common mistake is thinking the variable IS the object. It is not – the variable holds a reference (memory address) that points to the object. This distinction matters when you assign one object variable to another (covered in the Object References page).

Attributes

Attributes (also called fields or instance variables) store the data that defines an object’s state. Each object has its own copy of every attribute.

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

Attributes are typically declared private to enforce encapsulation – other classes cannot access or modify them directly. They must go through methods.

Choose the right data type for each attribute. This is a common exam question: “State the most appropriate data type for each attribute.” For example: name is String, age is int, gpa is double, isEnrolled is boolean, studentID is String (not int, because IDs can have leading zeros or letters).

Methods

Methods define what an object can do – its behaviour. Methods can read attributes, modify attributes, perform calculations, and interact with other objects.

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

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

    // Accessor method (getter) -- reads an attribute
    public double getBalance() {
        return balance;
    }

    // Accessor method (getter)
    public String getOwner() {
        return owner;
    }

    // Mutator method (setter/modifier) -- changes an attribute
    public void deposit(double amount) {
        if (amount > 0) {
            balance = balance + amount;
        }
    }

    // Method with logic -- reads attributes and returns a result
    public boolean canWithdraw(double amount) {
        return amount > 0 && amount <= balance;
    }

    // Mutator method with validation
    public void withdraw(double amount) {
        if (canWithdraw(amount)) {
            balance = balance - amount;
        }
    }
}

Method types:

  • Accessor (getter): returns the value of a private attribute without changing it. Named getAttributeName() or isAttributeName() for booleans.
  • Mutator (setter/modifier): changes the value of a private attribute, typically with validation. Named setAttributeName() or a descriptive verb like deposit(), withdraw().

Multiple Objects, Same Class

You can create as many objects from a class as you need. Each is independent:

BankAccount savings = new BankAccount("Alice", 5000.0);
BankAccount checking = new BankAccount("Alice", 1200.0);
BankAccount business = new BankAccount("Bob's Shop", 50000.0);

savings.deposit(500.0);
// Only savings.balance changes. checking and business are unaffected.

System.out.println(savings.getBalance());   // 5500.0
System.out.println(checking.getBalance());  // 1200.0
System.out.println(business.getBalance());  // 50000.0

Arrays of Objects

Just as you can create arrays of int or String, you can create arrays of objects:

// Assuming a Student class with constructor(String name, int grade)
// and a getName() accessor method

Student[] roster = new Student[30];  // array of 30 Student references

roster[0] = new Student("Alice", 11);
roster[1] = new Student("Bob", 11);
// roster[2] through roster[29] are still null

// Loop through and print names (with null check)
for (int i = 0; i < roster.length; i++) {
    if (roster[i] != null) {
        System.out.println(roster[i].getName());
    }
}

Creating an array of objects does NOT create the objects themselves. new Student[30] creates an array of 30 null references. You must instantiate each object separately with new Student(...). Always check for null before calling methods on array elements.


Worked Examples

Example 1: Designing a Class from Requirements

Scenario: A gym needs to track its members. Each member has a name, membership type (“basic” or “premium”), and months remaining on their membership.

Step 1: Identify attributes

Attribute Type Why
name String Text data
membershipType String “basic” or “premium”
monthsRemaining int Whole number of months

Step 2: Identify methods

Method Return type Purpose
getName() String Accessor for name
getMembershipType() String Accessor for membership type
getMonthsRemaining() int Accessor for months
renewMembership(int months) void Add months to membership
isExpired() boolean Check if months remaining is 0

Step 3: Write the class

public class Member {
    private String name;
    private String membershipType;
    private int monthsRemaining;

    public Member(String name, String membershipType, int monthsRemaining) {
        this.name = name;
        this.membershipType = membershipType;
        this.monthsRemaining = monthsRemaining;
    }

    public String getName() { return name; }
    public String getMembershipType() { return membershipType; }
    public int getMonthsRemaining() { return monthsRemaining; }

    public void renewMembership(int months) {
        if (months > 0) {
            monthsRemaining = monthsRemaining + months;
        }
    }

    public boolean isExpired() {
        return monthsRemaining <= 0;
    }
}

Example 2: Using Objects in Main

public class Main {
    public static void main(String[] args) {
        Member m1 = new Member("Alice", "premium", 6);
        Member m2 = new Member("Bob", "basic", 0);

        System.out.println(m1.getName() + " expired: " + m1.isExpired());
        System.out.println(m2.getName() + " expired: " + m2.isExpired());

        m2.renewMembership(12);
        System.out.println(m2.getName() + " expired: " + m2.isExpired());
        System.out.println(m2.getName() + " months: " + m2.getMonthsRemaining());
    }
}

Output:

Alice expired: false
Bob expired: true
Bob expired: false
Bob months: 12

Quick Check

Q1. What is a class in OOP?

Q2. What does new Student("Alice", 11) do?

Q3. What does Book[] shelf = new Book[5]; create?

Q4. What type of method is getBalance()?

Q5. If acc1 and acc2 are both BankAccount objects, and you call acc1.deposit(100), what happens to acc2?


Trace Exercise

Trace through this code. Track the state of each object after each line.

Trace: Multiple Objects

Book b1 = new Book("1984", "Orwell", 328);
Book b2 = new Book("Dune", "Herbert", 412);
Book b3 = new Book("Hamlet", "Shakespeare", 150);
ObjecttitleauthorpagesisLong()?
b1
b2
b3

Spot the Error

This code crashes with a NullPointerException. Click the buggy line, then pick the fix.

1Student[] roster = new Student[3]; 2// Expecting 3 students to be created automatically 3System.out.println(roster[0].getName());

Pick the fix:


Predict the Output

What does this code print?

Member m = new Member("Alice", "basic", 0);
System.out.println(m.isExpired());
m.renewMembership(6);
System.out.println(m.isExpired());

Type both lines of output separated by \n:


Practice Exercises

Core

  1. Create a Product class – A shop tracks products. Each product has a name (String), price (double), and quantity in stock (int). Write the class with a constructor, getters for all attributes, a method sell(int amount) that reduces the quantity (only if enough stock), and a method isInStock() that returns true if quantity is greater than 0.

  2. Use your Product class – In a Main class, create 3 Product objects, sell some items from one of them, and print the stock status of all three.

  3. Data type identification – For each of these attributes, state the most appropriate Java data type and explain your choice:

    • (a) A student’s full name
    • (b) The number of absences this semester
    • (c) Whether a student has submitted their assignment
    • (d) A student’s GPA (e.g., 3.75)
    • (e) A student’s ID number (e.g., “STU-00142”)

Extension

  1. Array of objects – Create an array of 5 Product objects. Write a loop that finds and prints the name of the most expensive product. Include null checks.

  2. Method design – Add a method restock(int amount) to your Product class that increases the quantity. Add validation: the amount must be positive and the total stock cannot exceed 1000. Test it with edge cases.

Challenge

  1. Full system – Design and implement a Classroom class that stores an array of Student objects (max 35). Include methods to:
    • Add a student
    • Remove a student by name
    • Find the student with the highest GPA
    • Calculate the class average GPA
    • Print all students with GPA above a given threshold

Connections

  • Prerequisites: What is OOP? – the four principles and key terminology
  • Prerequisites: Programming Constructs – how to define and call methods (selection, iteration, methods)
  • Next: Constructors – deeper dive into how objects are initialised
  • Related: 1D Arrays – arrays of objects follow the same patterns as arrays of primitives

Back to top

© EduCS.me — A resource hub for IB Computer Science

This site uses Just the Docs, a documentation theme for Jekyll.