Java: Advantage of static members

This entry is part 34 of 54 in the series Learn Java

The advantage of static members is that they can be used by other classes without having to create an instance of the class. Fields should therefore be declared static when only a single instance of the variable is needed.

Methods should be declared static if they perform a generic function that is independent of any instance variables.

A good example of this is the Math class which contains only static methods and fields.

double pi = Math.PI;

Math is one of the classes that are included by default in every Java application. The reason for this is because it belongs to the java.lang package, which is always imported.

This package contains classes fundamental to the Java language, such as: String,Object and System.

package javaapplication26;

public class StaticMembers {

    public static void main(String[] args) {
        double pi = Math.PI;       


Series Navigation<< Java: Accessing static members
Java: Static variables >>

Leave a comment

Leave a Reply