3.7 Class Variables and Methods

17 阅读1分钟

1. Exam Points

  • Access class variables or methods using a class name.
  • Access instance variables or methods using an instance name.
  • The value of final variables(constants) can not be changed.
  • If you want to count how many objects of a class is created, use a static variable.(Ex. static int count)

2. Knowledge Points

(1) Class Variables and Methods

  • Class variables and methods are declared using the static keyword.
  • Class variables belong to the class, with all objects of a class sharing it. (ex. pi is shared by all circles)
  • Class variables or methods can be accessed by external classes using the class name.
  • If you want to count number of objects created for a class, make the count variable static.
  • Example:
    image.png
  • Class methods from the same class can access class variables and class methods directly without creating an object. image.png

(2) Final Variables

  • When a variable is declared final, its value cannot be modified.
  • Example: final int x = 10;
    • The value of x can not be changed since it is declared as final
    • It is recommended to name a final variable using uppercase.
      • Example: final int ERROR_CODE = 404;

3. Exercises