Java: Class Variable/Static Variable

时间:2021-07-11 07:47:23

1. Class Variable/Static Variable:

  • Class variable is also known as static variable with "static" keyword inside the class but outside the methods.
  • There is only one copy of class variable is no matter how many objects are initiated from this class.
  • Class variable is accessed as: className.classVariableName.
  • Static variable is pretty like constant, declared with key word "static", stored in static memory, created when program begins and destroyed when program ends.

2. Java Static Method:

  • A static method belongs to a class rather than a object.
  • A static method could be invoked without creating an object.
  • Static method could access and change static data value.

3. Static Block:

  • It is used to initialize static data member.
  • It is executed before main method at the time of class loading.

4. Static Class:

  • There is inner class nested in outer class, inner class could be static class, out class can't be static class.
  • Inner static class doesn't need reference of outer class, but inner non-static class need reference of outer class.
  • Inner static class could only access outer static members of outer class.
  •  class OuterClass{
    private static String msg = "GeeksForGeeks"; // Static nested class
    public static class NestedStaticClass{ // Only static members of Outer class is directly accessible in nested
    // static class
    public void printMessage() { // Try making 'message' a non-static variable, there will be
    // compiler error
    System.out.println("Message from nested static class: " + msg);
    }
    } // non-static nested class - also called Inner class
    public class InnerClass{ // Both static and non-static members of Outer class are accessible in
    // this Inner class
    public void display(){
    System.out.println("Message from non-static nested class: "+ msg);
    }
    }
    }
    class Main
    {
    // How to create instance of static and non static nested class?
    public static void main(String args[]){ // create instance of nested Static class
    OuterClass.NestedStaticClass printer = new OuterClass.NestedStaticClass(); // call non static method of nested static class
    printer.printMessage(); // In order to create instance of Inner class we need an Outer class
    // instance. Let us create Outer class instance for creating
    // non-static nested class
    OuterClass outer = new OuterClass();
    OuterClass.InnerClass inner = outer.new InnerClass(); // calling non-static method of Inner class
    inner.display(); // we can also combine above steps in one step to create instance of
    // Inner class
    OuterClass.InnerClass innerObject = new OuterClass().new InnerClass(); // similarly we can now call Inner class method
    innerObject.display();
    }
    }