Class Variables and Methods
Use class variables/methods for shared states.
1. Reference Guide
| Concept | Key idea | Java example | Important note |
|---|---|---|---|
| Instance variable | Belongs to an individual object | private String name; |
Every object gets its own copy |
| Class variable | Belongs to the class and is shared by all objects | private static int numberOfStudents; |
Declared with static |
static |
Makes a variable/method belong to the class rather than an instance | public static int count; |
Access class members through the class when appropriate |
| Public class variable | A class variable accessible outside its class | public static int players; |
Access with Game.players |
| Class method | A method belonging to the class | public static int doubleValue(int x) |
Can be called without creating an object |
| Static method access | Static methods can access static/class members | count++ |
They cannot directly access instance variables |
| Dot operator | Used to access public class members | MathHelper.doubleValue(5) |
Typically ClassName.member |
final variable |
A variable whose value cannot be reassigned after initialization | public static final int DAYS_IN_WEEK = 7; |
Often used for constants |
| Shared state | All instances see the same class-variable value | Student.numberOfStudents |
Changing it affects what all objects see |
| Constructor + static variable | A constructor can update shared class state | numberOfStudents++; |
Useful for tracking how many objects have been created |
2. LxD Design Process
- Baseline. Students already understand instance vars/obj, so treat that as a bridge.
- Contrast instance vars with
staticclass vars before introducting static methods. - Use concrete code examples to demonstrate shared state (
Student.numberOfStudents) - Misconceptions. show that a static method cannot directly access an instance variable
- Introduce
finalafterstaticso students can distinguish shared from immutable - Apply. Follow TODOs to develop the
BankAccountclass with automated tasks.
3. Collegeboard Requirements
- 3.7.A Develop code to define behaviors of a class through class methods.
- 3.7.A.1 Class methods cannot access or change the values of instance variables or call instance methods without being passed an instance of the class via a parameter.
- 3.7.A.2 Class methods can access or change the values of class variables and can call other class methods
- 3.7.B Develop c
4. Lesson Objectives/Plan
- Define class variables and class methods using
static - Explain how class variables are shared by all objects of a class, and what class methods can/cannot access
- Use a class name and dot operator to access public class variables/methods
- Explain what the
finalkeyword does
5. Code Examples
Instance vs. Class Variables
Recall that an instance variable belongs to an individual object, so let’s say we have:
Code Runner Challenge
Modify the code so that creating each `Student` automatically increments the shared `numberOfStudents` counter.
View IPYNB Source
public class Student {
private String name;
private int grade;
}
and we define 3 students
Code Runner Challenge
Fix the code so that `printName()` can still be a `static` method. You might have to change what the method accepts.
View IPYNB Source
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
Each student gets their own name and grade.
Class variables are different in that they belong to the class itself:
public class Student {
private String name;
private int grade;
public static int numberOfStudents = 0;
}
Now, each student s1, s2, s3, shares one copy of numberOfStudents.
For example, we could make a class:
public class Student {
private String name;
public static int numberOfStudents = 0;
public Student(String n) {
name = n;
numberOfStudents++;
}
}
and create a few objects:
Student a = new Student("Alice");
Student b = new Student("Bob");
Student c = new Student("Charlie");
which makes Student.numberOfStudents 3.
Static
We use static to denote that a variable or method belongs to the class itself rather than to an individual object.
This would be an instance variable:
private String name;
and this would be a class variable:
private static int numberOfStudents;
Public and Private
If we want some class variable to be accessible outside of the class, we can declare it as public:
public class Game {
public static int players = 0;
}
which means we can do:
System.out.println(Game.players); // get # of players
Game.players = 5; // modify # of players
Class Methods
Similarly, we can define a method as static to denote it belongs to a class:
public class MathHelper {
public static int doubleValue(int x) {
return x * 2;
}
}
Now we can call it without creating a MathHelper object:
int result = MathHelper.doubleValue(5);
System.out.println(result); // 10
Class methods can access class variables, other class methods, its parameters, and local variables, but NOT instance variables:
public class Counter {
private static int count = 0;
public static void increase() {
count++;
}
public static int getCount() {
return count;
}
public static void reset() {
count = 0;
}
public static void resetAndIncrease() {
reset();
increase();
}
}
We CANNOT do this
public class Student {
private String name;
public static void printName() {
System.out.println(name); // ERROR
}
}
final Variables
We define a variable as final if we want it to be immutable.
public static final int DAYS_IN_WEEK = 7;
6. Hacks
Popcorn Hack #1
// CODE_RUNNER: Modify the code so that creating each `Student` automatically increments the shared `numberOfStudents` counter.
public class Student1 {
private String name;
public static int numberOfStudents = 0;
public Student1(String name) {
this.name = name;
// TODO: Increment the shared student counter
}
public static void main(String[] args) {
Student1 a = new Student1("Alice");
Student1 b = new Student1("Bob");
Student1 c = new Student1("Charlie");
System.out.println(Student1.numberOfStudents); // 3
}
}
Student1.main(null);
Popcorn Hack #2
// CODE_RUNNER: Fix the code so that `printName()` can still be a `static` method. You might have to change what the method accepts.
public class Student2 {
private String name;
public Student2(String name) {
this.name = name;
}
public static void printName() {
System.out.println(name);
}
public static void main(String[] args) {
Student2 s = new Student2("Alice");
Student2.printName();
}
}
Student.main(null);
Homework
In this assignment, you’ll be modifying a partially implemented Java class called BankAccount.
Unzip the file under _projects/lessons/java/static/3-7_bank.zip, which contains a simple Java Maven project. Complete the TODOs listed, and run tests using mvn test. Submit your source BankAccount.java file (see below).
Rubric
| Component | Criteria | Number | Points Each | Total |
|---|---|---|---|---|
| Popcorn Hack 1 | Student correctly implements the shared static counter |
1 | 0.15 | 0.15 |
| Popcorn Hack 2 | Student correctly modifies the static method to work with instance data | 1 | 0.15 | 0.15 |
| Homework Unit Tests | Each passing unit test demonstrates correct implementation of the BankAccount requirements |
10 | 0.06 | 0.60 |
| Total | 12 | 0.90 |
Submission
- Create a new notebook in your portfolio homework area: _notebooks/homework.
- Add one raw cell at the top with the frontmatter:
--- layout: post codemirror: true title: Class Variables and Methods HW categories: [Java] lesson_language: Java lesson_topic: Class-Variables-and-Methods HW lesson_part: interactive lesson_type: lesson permalink: /csa/unit_03/3_7-hw author: <yourGithubID> ---
Add a code cell with the BankAccount code snippet (or just run it directly by importing it as a .java file), then submit the notebook/Java file with these details:
Lesson: CSA 3.7 Class Methods and Variables
Popcorn Hack 1: completed? (y/n)
Popcorn Hack 2: completed? (y/n)
Homework: tests passed (x/10)
Submit Assignment
Self-Assessment
Rate your work on this assignment, then add a short reflection. All 5 fields are required before you can submit.
Need to update a submission later? Open the submissions dashboard.