B3.1.3 · OOP for a single class
Static vs instance members
By the end you can
Contrast class-level static members and heap-allocated instance variables, explaining memory and invocation rules.
Inside a class definition, variables and methods can be declared either as (the default) or as (using the static keyword). Understanding how the runtime handles memory for each is critical to writing bug-free object-oriented software.
Instance members: Unique to each object#
Every time you create an object using new Student(), a fresh set of instance variables is allocated on the heap. If you instantiate 100 Student objects:
- There are 100 independent copies of
nameandstudentIdin RAM. - Mutating the name of student 1 has zero effect on student 2.
- Instance methods are invoked using an object reference:
student1.getGrade().
Static members: Shared by the whole class#
A member marked with the static keyword belongs to the class itself rather than any individual instance:
- Single shared copy: Only one copy of a static variable exists in memory, regardless of whether you instantiate zero, one, or 10,000 objects.
- Global counters / IDs: A classic use case is an auto-incrementing ID generator:
public class Student { private static int nextId = 1000; // Shared class counter private int id; // Unique per student public Student() { this.id = nextId++; // Assign and increment shared counter } } - Utility functions: Methods that perform mathematical calculations without needing object state are declared static (e.g.
Math.pow(2, 8),Integer.parseInt("42")).
Check yourself
Static and instance members
Quick questions, made fresh every time and marked here. Do a few until they feel easy.
Exam practice
Paper 1-style questions
3 questions · 8 marks
Write your answer as you would in the exam, then show the mark points and tick each one your answer made. These are our own questions in the style of the exam, not past-paper questions.
1.Compare static (class) members and instance members in terms of memory allocation, ownership, invocation syntax, and common use cases.
[4]Compare: Similarities and differences, about both things, point by point.
2.Explain why a static method cannot directly reference instance variables or use the 'this' keyword.
[2]Explain: Give reasons: say what happens AND why, or how one thing causes another.
3.Construct a class design outline showing how a static variable can be used to track the total number of instantiated objects.
[2]Construct: Draw or write it out (a table, a diagram, a program).
In a nutshell
- Static members belong to the class as a single shared entity; instance members belong to individual objects.
- Static variables are allocated once when the class is loaded into memory, shared by all instances.
- Static methods are invoked using the class name (e.g. Math.sqrt(x)) without creating an object instance.
- Static methods cannot access instance variables or use the "this" keyword because they have no object context.
