Class (static) Variables and Methods

 

Python

Java

 

Class variables name data that are shared by all instances of a class.

 

A class variable is introduced by a simple assignment statement within a class. 

 

Class variable references are always prefixed with the name of the class.

 

Class variables are spelled in uppercase by convention.

 

Example:

 

class Student:

 

    NUM_GRADES = 5

 

    def __init__(self, name):

        self.name = name

        self.grades = []

        for i in range(Student.NUM_GRADES):

            self.grades.append(0)

 

 

 

 

Other usage:

 

print(Student.NUM_GRADES)

 

Class methods are methods that know nothing about instances of a class, but can access class variables and call other class methods for various purposes.  For example, a method to convert a numeric grade to a letter grade might be defined as a class method in the Student class.

 

Class method calls are always prefixed with the name of the class.

 

Example:

 

class Student:

 

    # Instance method definitions

 

       @classmethod

    def getLetterGrade(cls, grade):

        if grade > 89:

            return 'A'

        elif grade > 79:

            return 'B'

        else:

            return 'F'

 

Usage:

 

s = Student()

for i in range(1, Student.NUM_GRADES + 1):

    print(Student.getLetterGrade(s.getGrade(i)))

 

Class variables name data that are shared by all instances of a class.

 

A class variable declaration is qualified by the reserved word static. 

 

Outside of the class definition, class variable references are prefixed with the name of the class.

 

Class variables are spelled in uppercase by convention.

 

 

 

Example:

 

public class Student{

 

    public static final int NUM_GRADES = 5;

 

    private String name;

    private int[] grades;

 

    public Student(String name){

        this.name = name;

        this.grades = new int[NUM_GRADES];

    }

}

 

Other usage:

 

System.out.println(Student.NUM_GRADES);

 

Class methods are methods that know nothing about instances of a class, but can access class variables and call other class methods for various purposes.  For example, a method to convert a numeric grade to a letter grade might be defined as a class method in the Student class.

 

A class method header is qualified by the reserved word static.

 

Outside of the class definition, class method calls are prefixed with the name of the class.

 

Example:

 

public class Student{

 

    // Instance method definitions and variable declarations

 

    public static char getLetterGrade(int grade){

        if (grade > 89)

            return 'A';

        else if (grade > 79)

            return 'B';

        else

            return 'F';

 

 

Usage:

 

s = new Student();

for (int i = 1; i <= Student.NUM_GRADES; i++)

    System.out.println(Student.getLetterGrade(s.getGrade(i));

 

Previous

Index

Next