Static Variables and Methods

A modifier you already have used in programs is static, which was introduced during Day 6, "Creating Classes and Methods." The static modifier is used to create class methods and variables, as in the following example:

public class Circle { 
    public static float pi = 3.14159265F;
    
    public float area(float r) { 
        return  pi * r * r;
    }
}

Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method, as in Color.black or Circle.pi. You also can use the name of an object of the class, but for class variables and methods, using the class name is better. This approach makes clearer what kind of variable or method you're working with; instance variables and methods can ...

Get Sams Teach Yourself Java 2 in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.