IB COMPUTER SCIENCE | B3.1.3 Static and Non-static Members

Lesson objective

Distinguish class-level and instance-level variables and methods, explain their usage and scope, and choose suitable members for shared and independent state.

Learn

B3.1.3 | STATIC AND INSTANCE MEMBERS

01 | WHICH INFORMATION BELONGS TO ONE STUDENT?

Two students attend the same school, but each has a different name and quiz score. If the program stores only one shared score, adding marks to Ada could change the value seen for Lin. If every object separately stores a shared school policy, keeping it consistent can become harder.

The central distinction is class-level versus instance-level membership. Class-level data describes the class as a whole; instance data belongs to a particular object. Methods also differ in whether they receive an object automatically.

This common SL/HL lesson uses Java’s static/non-static terminology and the corresponding Python class attributes, instance attributes and static methods. Their details are related, but not identical.

02 | STATIC VARIABLES: CLASS-LEVEL MEMBERS

In Java, a static field belongs to a class rather than a separate field in every object. In our Student example, a school label and a count of created students can be class-level values.

Python normally expresses this through attributes assigned in the class body, such as school = "Cafe College". Python has no static keyword for declaring these attributes.

A class-level value is shared through that class definition, not automatically across every program, server or saved database. Restarting a program does not preserve an in-memory counter unless persistence is separately implemented.

03 | NON-STATIC VARIABLES: INSTANCE STATE

An instance variable belongs to a particular object. Ada’s name and score must be independent of Lin’s name and score. In Python, assigning self.score inside initialization establishes that instance attribute.

In Java, a field without static is an instance field. Constructing two objects gives each its own score field, even though their methods are defined in one class.

The right choice follows meaning. “Every student starts at score 0” does not mean there should be one shared score: the equal initial values must still be able to change independently.

04 | COMPARE OWNERSHIP SIDE BY SIDE

Feature Class-level / Java static Instance-level / Java non-static
Owner The class A particular object
Example data Student.created_count ada.score
Copies of field state One per relevant class definition Separate instance fields per object
Typical access ClassName.member object.member
Appropriate meaning Shared metadata, policy or class-wide count Identity, balance, score or state of one entity

These are ownership distinctions, not access permissions. A field can be private static or private non-static; private does not imply instance state.

A class-level reference can also point to a shared mutable object. “One field” does not imply its value is immutable or safe from unintended changes.

05 | A COMPLETE PYTHON EXAMPLE

class Student:
    school = "Cafe College"
    created_count = 0

    def __init__(self, name):
        self.name = name
        self.score = 0
        Student.created_count = Student.created_count + 1

    def add_points(self, points):
        if type(points) is not int or points < 0 or self.score + points > 100:
            return False
        self.score = self.score + points
        return True

    @staticmethod
    def is_valid_score(value):
        return type(value) is int and 0 <= value <= 100

school and created_count are class attributes. name and score are created on each instance in __init__. add_points uses the receiving student’s score. is_valid_score is explicitly decorated as a static method.

The constructor assumes a suitable name. Point updates accept non-negative integers only when the resulting score is at most 100; rejected updates return False without changing the score.

created_count is incremented after instance state is initialized. It counts instances constructed through this initializer during this run, not the number currently alive or records stored permanently.

06 | CREATE TWO OBJECTS AND READ THE CLASS

class Student:
    school = "Cafe College"
    created_count = 0

    def __init__(self, name):
        self.name = name
        self.score = 0
        Student.created_count = Student.created_count + 1

    def add_points(self, points):
        if type(points) is not int or points < 0 or self.score + points > 100:
            return False
        self.score = self.score + points
        return True

    @staticmethod
    def is_valid_score(value):
        return type(value) is int and 0 <= value <= 100

ada = Student("Ada")
lin = Student("Lin")
print(Student.created_count)
print(ada.name, ada.score)
print(lin.name, lin.score)
print(Student.school)

The output lines are 2, Ada 0, Lin 0 and Cafe College. The shared creation count increased twice, while two separate score values were initialized.

Read Student.created_count as a class-level fact and ada.score as a fact about one receiver. Naming the owner explicitly helps readers distinguish the two.

07 | AN INSTANCE METHOD USES ITS RECEIVER

class Student:
    school = "Cafe College"
    created_count = 0

    def __init__(self, name):
        self.name = name
        self.score = 0
        Student.created_count = Student.created_count + 1

    def add_points(self, points):
        if type(points) is not int or points < 0 or self.score + points > 100:
            return False
        self.score = self.score + points
        return True

    @staticmethod
    def is_valid_score(value):
        return type(value) is int and 0 <= value <= 100

ada = Student("Ada")
lin = Student("Lin")
print(ada.add_points(10))
print(ada.score, lin.score)

The outputs are True, then 10 0. In ada.add_points(10), self refers to ada. The assignment self.score changes Ada’s score, while Lin’s remains 0.

An ordinary Python instance method receives that instance automatically through the bound call. A Java instance method similarly has a current this reference.

The method may also read class-level metadata if its task needs it. Instance methods are not forbidden from accessing class members.

08 | A STATIC METHOD HAS NO AUTOMATIC INSTANCE

A static method does not receive a particular object automatically. Our validation rule checks a supplied value and does not need to know whether Ada or Lin is calling.

Use Student.is_valid_score(85). There is no implicit self and no hidden student score to inspect. Java expresses this with static; Python uses @staticmethod.

A static method can still work with an object explicitly passed as an argument, or refer to a class by name. “No automatic instance” is more precise than “static code can never access any object”.

09 | CALL VALIDATION WITHOUT CONSTRUCTING A STUDENT

class Student:
    school = "Cafe College"
    created_count = 0

    def __init__(self, name):
        self.name = name
        self.score = 0
        Student.created_count = Student.created_count + 1

    def add_points(self, points):
        if type(points) is not int or points < 0 or self.score + points > 100:
            return False
        self.score = self.score + points
        return True

    @staticmethod
    def is_valid_score(value):
        return type(value) is int and 0 <= value <= 100

print(Student.is_valid_score(85))
print(Student.is_valid_score(105))
print(Student.is_valid_score("85"))
print(Student.created_count)

The output is True, False, False, then 0. The class exists, but no Student instance was created. The static method checks the explicit argument rather than a student’s current score.

The rule accepts actual Python int values from 0 to 100. A text representation "85" must be converted elsewhere. This definition also deliberately excludes Boolean values, whose Python type relationship can otherwise surprise learners.

The class count remaining 0 demonstrates that calling this utility does not instantiate an object.

10 | A CLASS UPDATE VERSUS AN INSTANCE UPDATE

class Student:
    school = "Cafe College"
    created_count = 0

    def __init__(self, name):
        self.name = name
        self.score = 0
        Student.created_count = Student.created_count + 1

    def add_points(self, points):
        if type(points) is not int or points < 0 or self.score + points > 100:
            return False
        self.score = self.score + points
        return True

    @staticmethod
    def is_valid_score(value):
        return type(value) is int and 0 <= value <= 100

ada = Student("Ada")
lin = Student("Lin")
Student.school = "Mountain School"
ada.add_points(10)
print(ada.school, lin.school)
print(ada.score, lin.score)

The first output is Mountain School Mountain School; the second is 10 0. Neither instance has its own school attribute, so Python finds school on Student. The score update uses Ada’s separate instance state.

This does not mean all attributes accessed through an object are stored on that object. Python attribute lookup can fall back to the class. The next example exposes why that distinction matters.

11 | PYTHON SHADOWING: ASSIGNING THROUGH ONE OBJECT

class Student:
    school = "Cafe College"
    created_count = 0

    def __init__(self, name):
        self.name = name
        self.score = 0
        Student.created_count = Student.created_count + 1

    def add_points(self, points):
        if type(points) is not int or points < 0 or self.score + points > 100:
            return False
        self.score = self.score + points
        return True

    @staticmethod
    def is_valid_score(value):
        return type(value) is int and 0 <= value <= 100

ada = Student("Ada")
lin = Student("Lin")
ada.school = "Ada Academy"
Student.school = "Mountain School"
print(Student.school)
print(ada.school)
print(lin.school)

Outputs: Mountain School, Ada Academy, Mountain School. ada.school = ... creates an instance attribute that shadows the class attribute for this ordinary attribute design. It does not change Student.school.

Lin still falls back to the updated class value. Ada’s own value takes precedence for ada.school. This Python behaviour is not the rule for assigning a Java static field through an instance expression.

When the intention is a shared class update, use an explicit class-level operation or ClassName.attribute assignment with a clear contract.

12 | WHY SELF.COUNT += 1 CAN BE WRONG

class WrongCounter:
    count = 0

    def __init__(self):
        self.count = self.count + 1

a = WrongCounter()
b = WrongCounter()
print(WrongCounter.count, a.count, b.count)

The output is 0 1 1. For each new object, the right side first finds the class value 0, but the assignment stores a new instance count of 1. The class count was not incremented.

For the intended one-class creation counter, use WrongCounter.count = WrongCounter.count + 1 instead. self.count += 1 has the same shadowing issue with this integer attribute.

These examples use plain attributes. More advanced descriptors or properties can alter assignment behaviour; the lesson’s prediction is for the shown class design.

13 | SHARED MUTABLE ATTRIBUTES: A DIFFERENT PITFALL

class WrongStudent:
    scores = []

a = WrongStudent()
b = WrongStudent()
a.scores.append(8)
print(b.scores)
print(WrongStudent.scores)

Both outputs are [8]. No instance scores attribute was assigned: both objects found the same class-level list, and append mutated that shared object.

This differs from rebinding ada.school. Mutation changes an existing object; assignment to an instance attribute can establish a new binding.

If each student needs their own list, initialize self.scores = [] inside __init__, so each construction creates a separate list.

14 | CORRECT INDEPENDENT COLLECTIONS

class StudentScores:
    def __init__(self, name):
        self.name = name
        self.scores = []

a = StudentScores("Ada")
b = StudentScores("Lin")
a.scores.append(8)
print(a.scores)
print(b.scores)

Outputs: [8] and []. The separate lists have the same initial contents but different identities. One object’s append does not affect the other.

Use a class-level collection only when shared collection state is actually required, such as a deliberately managed registry. Then define lifecycle, memory and update rules rather than assuming sharing is always wrong.

15 | INTERACTIVE: FOLLOW CLASS AND INSTANCE STATE

Step through a supplied Python sequence. The display separates attributes stored on Student from attributes stored on ada and lin. A school value found through class lookup is labelled differently from an instance override.

Predict the shared count, Ada’s score and the two visible school values before each step. Notice that a static validation call does not create a Student, and deleting an instance override later reveals the class value again.

16 | JAVA: EXPLICIT STATIC AND NON-STATIC MEMBERS

public class StudentExample {
    static class Student {
        static String school = "Cafe College";
        static int createdCount = 0;
        String name;
        int score;

        Student(String name) {
            this.name = name;
            this.score = 0;
            Student.createdCount++;
        }

        void addPoints(int points) {
            if (points < 0 || points > 100 - this.score) {
                throw new IllegalArgumentException("Invalid points");
            }
            this.score = this.score + points;
        }

        static boolean isValidScore(int value) {
            return value >= 0 && value <= 100;
        }
    }

    public static void main(String[] args) {
        Student ada = new Student("Ada");
        Student lin = new Student("Lin");
        ada.addPoints(10);
        Student.school = "Mountain School";
        System.out.println(Student.createdCount);
        System.out.println(ada.score + " " + lin.score);
        System.out.println(Student.isValidScore(85));
    }
}

The outputs are 2, 10 0 and true. school and createdCount have explicit static declarations; name and score do not. The utility can be called through Student without choosing a student instance.

The nested Student class keeps this demonstration in one source file. Its static nested-class declaration is a separate issue from whether its members are static. score remains an instance field.

Java addPoints here throws for invalid points, whereas the earlier Python method returns False. Both guard state, but their caller contracts differ; do not assume identical failure interfaces merely because the purpose is similar.

17 | WHY JAVA MAIN CANNOT SIMPLY USE THIS.SCORE

A static Java method has no current instance, so this cannot be used in that static context. To work with a student’s score, receive or construct a Student reference and access its permitted instance operations.

In the example, main creates ada and then calls ada.addPoints(10). Static code is using an explicitly referenced object, rather than receiving an implicit this.

Similarly, a Python @staticmethod has no self parameter supplied automatically. A bare reference to an undeclared self is not a way to select whichever object the author had in mind.

18 | CALL STYLE CAN HIDE THE OWNERSHIP

Java permits some static-member access through an instance expression, but the member remains class-level; this does not create Python-style instance shadowing for a static field. Prefer ClassName.member to communicate the intended ownership.

Python also permits calling a static method through an instance. That call still does not bind self. ClassName.method(...) usually makes the purpose clearer for this lesson’s utilities.

Read the declaration and operation semantics, not only the expression to the left of the dot. The same-looking object.member text can mean different things across languages and member kinds.

19 | PYTHON CLASS METHODS ARE A THIRD CATEGORY

class SchoolSettings:
    school = "Cafe College"

    @classmethod
    def rename_school(cls, name):
        cls.school = name

SchoolSettings.rename_school("Mountain School")
print(SchoolSettings.school)

The output is Mountain School. @classmethod receives the class as cls automatically, rather than receiving an instance as self or receiving neither as @staticmethod does.

This can express an operation on class-level state. The distinction becomes more useful with subclasses, but the immediate point is simple: a class method and a static method are not interchangeable Python names.

The Java static method category does not automatically map to every Python class-level pattern one-to-one. State the language and binding rule.

20 | OWNERSHIP, SCOPE AND ACCESS ARE DIFFERENT

Question Meaning Example
Who owns the state? Class versus instance Student.created_count versus ada.score
Where is a name resolved? Scope / lookup A local parameter versus an attribute accessed through self
Who may use a member? Visibility / access control Java private versus public
Does the call get an object automatically? Method binding Python self versus @staticmethod

A private static counter is still class-level state. A public instance method still acts through a receiver. A local variable inside a static method is not a shared static field merely because of where the method is declared.

Static also does not mean constant. A static field can be mutable unless restrictions and design say otherwise; final in Java concerns reassignment and is a separate property.

21 | UML: UNDERLINE CLASS-LEVEL FEATURES

Student

school: String

createdCount: Integer

name: String

score: Integer

addPoints(points: Integer)

isValidScore(value: Integer): Boolean

Underlined members have classifier/class scope; the other shown members have instance scope. Visibility markers are omitted here to keep the ownership distinction clear.

UML underlining communicates scope. It does not mean the member is read-only, private or a database primary key. Keep notation tied to its purpose.

In a detailed design, retain operation contracts, access visibility and initialization rules alongside this distinction.

22 | CHOOSE CLASS STATE WHEN THE FACT IS CLASS-WIDE

A deliberately shared category label, configuration value or per-class creation counter can be a useful class member. A utility operation that only checks its explicit argument can be a static method if placing it on the class makes the interface cohesive.

Changing a shared setting can affect many callers, so centralize its update policy when necessary. Concurrent increments are not automatically safe just because they use a static field.

The counter in this lesson is not a persistent ID generator, an authoritative database count or a live-object tracker. Define exactly what a class-wide statistic measures.

23 | CHOOSE INSTANCE STATE WHEN OBJECTS MAY DIFFER

Names, quiz scores, balances, current borrowers and device settings often belong to specific objects. Even when the first two values happen to match, their future updates may differ.

An operation that acts on one such state should usually be an instance method. add_points clearly identifies the student being changed, while a static method would need that student supplied explicitly.

Shared mutable fields can accidentally couple otherwise independent objects. Ask “should changing Ada’s value affect Lin?” before choosing class-level storage.

24 | CONSTRUCT IT: A DEVICE MODEL

A device has its own deviceId and battery level. All instances share a manufacturer label and a count of creations. A utility validates a proposed battery level without inspecting any current device. Choose the member kinds before writing code.

Reveal an appropriate allocation
Member Kind Reason
deviceId Instance attribute Identifies one device
battery Instance attribute Devices discharge independently
manufacturer Class-level attribute Shared label in this model
createdCount Class-level attribute Counts this class’s construction events
usePower(amount) Instance method Changes one receiver’s battery
isValidBattery(value) Static utility Checks an explicit value without an implicit receiver

If different devices may legitimately have different manufacturer labels, that requirement changes the design: manufacturer should then be instance state. Sharedness follows the model, not the noun itself.

25 | COMMON ERRORS TO REPAIR

Confusion Correct distinction
Static means immutable Ownership is separate from mutability
All fields starting at 0 should be static Equal starting values may need independent updates
A local variable in a static method is shared It is local to that invocation
Python self.count increments the class integer Ordinary assignment can create an instance shadow
A class list always becomes a new list per instance Unshadowed lookups can share one mutable list
Static methods can never use objects They need explicit references rather than an automatic receiver
Python classmethod equals staticmethod classmethod binds cls; staticmethod binds neither cls nor self
A creation counter means live objects or saved records State exactly which events it counts

26 | ANSWER DISTINGUISH WITH THE KEY DIFFERENCES

For a Distinguish question, make the ownership and binding differences explicit. Class-level fields are associated with the class; instance fields belong to particular objects. Static methods lack an automatic instance; instance methods use a receiver.

Support the contrast with one shared fact and one independent fact, such as school versus score. If using Python, explain class attributes, shadowing and decorators accurately rather than simply inserting Java’s static keyword.

Then justify the choice from the requirements. The next lesson constructs classes and instantiates objects, applying these member decisions to complete programs.

MATCH THE MEMBER KIND

Terminology

Terminology

Static field

A Java field associated with a class rather than separate state in each instance.

Class attribute

A Python attribute stored on a class and found through suitable class lookup.

Instance variable

State stored separately for a particular object.

Non-static field

A Java instance field belonging to each object.

Static method

A method called without an automatically supplied current instance.

Instance method

A method operating through a receiving instance.

Receiver

The object associated with an instance-method call.

self

Conventional Python parameter for the bound receiving instance.

this

Java reference to the current instance in an instance context.

@staticmethod

Python decorator preventing automatic instance/class argument binding.

@classmethod

Python decorator binding the class as the first argument.

cls

Conventional parameter name for a bound class argument.

Attribute lookup

The process of resolving an attribute, which can include class lookup.

Shadowing

An instance attribute taking precedence over a same-named ordinary class attribute.

Rebinding

Making a name or attribute refer to a different value/object.

Mutation

Changing an existing object’s contents or state.

Shared mutable state

A changeable object accessible through multiple references or callers.

Local variable

A name belonging to a function/method invocation’s scope.

Scope

The context in which names are resolved.

Visibility

Rules governing access to a member.

Class-qualified access

Using ClassName.member to make class-level ownership explicit.

Initialization

Establishing initial state when an object is created.

Creation counter

A statistic counting construction events under a stated policy.

Instance override

An ordinary instance attribute hiding a class attribute in this example.

UML underlining

Notation indicating classifier/class scope for a feature.

Constant

A value intended not to change; a separate concept from static ownership.

Auxiliary utility

An operation that can work with explicit inputs without instance state.

Independent state

Values that can change for one object without changing another’s corresponding state.

Persistence

Keeping data beyond the current process through explicit storage.

Member contract

The specified inputs, effects, results and rejection behaviour of an operation.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which should be instance state in the stated Student model?
2. Which distinguish Java static and non-static fields?
3. Which describe Python class attributes?
4. Which describe instance methods?
5. Which describe the shown static validation utility?
6. Which follow after ada.school = "Ada Academy" for the ordinary Python class?
7. Which explain the class-list pitfall?
8. Which distinguish Python method categories?
9. Which statements about ownership and access are correct?
10. Which are valid design conclusions?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Distinguish static and non-static variables using the Student model.

2. Distinguish static and instance methods.

3. Trace two Student creations followed by ada.add_points(10).

4. Explain why a field should not be static merely because every object starts with the same value.

5. Trace ada.school = "Ada Academy" followed by Student.school = "Mountain School" in the shown Python class.

6. Explain why self.count = self.count + 1 can fail to increment a Python class counter.

7. Explain why a class-level list can accidentally couple student records.

8. Describe how Java static code can legitimately use instance state.

9. Distinguish Python classmethod and staticmethod.

10. Explain why visibility and static ownership should not be confused.

11. Construct a member allocation for independently discharging devices sharing one manufacturer label.

12. Explain two limitations of a simple class creation counter.

DISTINGUISH IT | SHARED AND INDIVIDUAL ACCOUNT DATA

Distinguish the appropriate member kinds for a BankAccount model: each account has an account ID and balance; all accounts in this simplified model share one bank label; a utility checks an explicitly supplied proposed balance; depositing changes one account. State why a shared balance would violate the requirement.

Reveal an allocation

accountId and balance are instance fields because accounts must remain distinct. The bank label is class-level under the stated shared-label model. deposit(amount) is an instance operation on the receiving account. A validation utility can be static when it uses only the supplied proposed value and needs no automatic receiver. A shared balance would make independent accounts use one class-level fact, so a deposit could incorrectly affect the value observed for others. These are model choices, not a complete financial-system design.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

Selections are kept while this page is open.

Workbook

Workbook

COMING SOON

The workbook for B3.1.3 Static and Non-static Members is coming soon. Complete the matching task and written questions in your exercise book.