Static Variables and Methods
Introduction: 5.7.0
Static
methods and variables belong to a class- called with the class name rather than using a specific object
- only one copy of a static variable or method
- can be public or private
- the static keyword is placed after the public/private modifier
- before the return type
- static methods only have access to other static variables and methods
- cannot access or change the values of instance variables
- can’t use
this
- there’s no object calling them!
- can’t use
- cannot access or change the values of instance variables
- only one instance of a static variable is generated
- useful for counting how many objects are generated
- keep track of a min/max/average in a collection of objects
Summary: 5.7.2
- Static methods and variables include the static keyword before their name in the header or declaration
- can be public or private
- static methods and variables belong to the class, with all objects sharing a single static variable
- used with the class name and the dot operator
- static methods cannot change the values of instance variables
- can access/change static variables
- static methods cannot call non-static methods
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.