Module 2 Static Class Members 10212021 1 Overview

Module 2 Static Class Members 10/21/2021 1

Overview Static Class Members discussed: • Static Variables • Static Methods within static classes • Examples of commonly used Static classes 10/21/2021 2

Static Variables • A Static variable is shared among all instances of a class • Also called a class variable • A variable become static by adding the reserved word static • e. g. static int no. Of. Cars =0; • A local variable cannot be static if the method is not static • Constants which are instance variables are often static because just having one copy is good enough. 10/21/2021 3

Static Methods • A Static method is invoked through a class name • A static method is also called a class method • An object is not instantiated • A method becomes static by adding the static reserved word to the method header: • public static int car. Count () • The main method in Java uses public static void main() • A static method can access only static variables and local variables 10/21/2021 4

Static Classes • This is only possible in nested classes where the inner class is static 10/21/2021 5

Static Variables & Methods - Example public class factory. Worker { private String name; private int emp. Id; private static int next. Id = 1; public int get. Id() { return emp. Id; } public void set. Id() { emp. Id = next. Id; // set id to next available id next. Id++; } } public static int get. Next. Id() { return next. Id; // returns static field } 10/21/2021 6

Static Variables & Methods - Example public class Static. Test { public static void main(String[] args) { factory. Worker fw = new factory. Worker(); } } int n = factory. Worker. get. Next. Id(); // calls static method System. out. println("Next available id=" + n); 10/21/2021 7

Commonly used Static Method • Math Class • abs () • min() • max() • sqrt() 10/21/2021 8

Summary • Static Methods can be accessed using a class name • Static variables are common across all instances of a class • The reserved word static is used to identify a variable or method as static 10/21/2021 CSE 1321 Module 6 9
- Slides: 9