Implement a static variable in a class
Create a class named Counter
with a static variable count
of type int
. Initialize it to 0. Then, create a method named increment
that increases the value of count
by 1 every time it is called. Finally, create a method named getCount
that returns the current value of count
.
Instructor solution
Think you've got it?
What is the purpose of a static variable in a class?
- A.
A static variable is unique to each instance of a class.
- B.
A static variable is a variable that cannot be changed.
- C.
A static variable can only be used inside static methods.
- D.
A static variable is shared among all instances of a class.
You may exit out of this review and return later without penalty.