static

  • In interface, static can be used to define utility functionality that is common for all classes implementing the interface.
  • It is not recommended to call static fields/methods using object reference, Always use class reference to refer static fields/methods
  • Example: System.out.println() is static method

Fields

  • static fields in class are known as Class Fields
  • They can be accessed by Class Name directly: ClassName.fieldName
  • Generally, declaring non-final public static fields is not a good practice

Constants

  • static final fields are also known as Class Constants
  • the naming convention is to use uppercase with underscores
  • They can only be initialized using static initialization block if they are not initialized when declared
  • See static initializer
class A {    
    private static final int x;
 
    static {
        x = 5;
    }
}

Methods

  • aka Class Methods
  • They have following features:
    • They can access only static fields and cannot access non-static fields
    • They can invoke another static method, but it cannot invoke an instance method
    • They cannot refer to this keyword because there is no instance in the static context
    • They cannot refer to super keyword
  • Instance methods, however, can access static fields and methods.
  • Only way to call instance methods from static method is to pass instance as an argument to static method
  • Examples:
    • Math.abs(val)Math.pow(x, y)
    • Long.valueOf(...)Integer.parseInt(...)String.valueOf(...)

static class

static initializer block