Java Keyword Static

The reserved keyword static is used to declare a Java variable, Java method, or Java inner class as a class field. Static classes maintain one copy of class fields regardless of how many instances of the class exists. Java class methods are bound to the class itself and not a specific instance, meaning they can only operate on class fields.

The following sample shows a class that includes a static variable, a static method and a non-static method.

//JavaCodeDepot Sample 

public class Vehicle {

    static String modelName;
     
    static void go() {

        //Code to go
    }
     
    void stop() {

        //Code to stop
    }
}


The static variable (modelName) and static method (go) can be access in a static way like the following code sample.

//JavaCodeDepot Sample 

Vehicle.modelName = "Corvette";
Vehicle.go();


The non-static method (stop) mist be accessed by an instance of the class.

//JavaCodeDepot Sample 

Vehicle vehicle = new Vehicle();
vehicle.stop();


While you can’t have a regular class that is static, you can have a static inner class as show below.

//JavaCodeDepot Sample 

public class Vehicle {

    static class Wheels {

    }
}


The static inner class (wheels) can be instantiated without the need to create an instance of the outside class Vehicle.

//JavaCodeDepot Sample 

Vehicle.Wheels vehicleWheels = new Vehicle.Wheels();


The complete list of Java reserved keywords contains a total of 50 keywords and 3 literal words that are unable to be used as variable names.

Add a Comment

Your email address will not be published. Required fields are marked *