What are the restrictions imposed on a static method or a static block of code in java?

JavaObject Oriented ProgrammingProgramming

static methods and static blocks

Static methods belong to the class and they will be loaded into the memory along with the class, you can invoke them without creating an object. (using the class name as reference).

Whereas a static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.

Example

 Live Demo

public class Sample {
   static int num = 50;
   static {
      System.out.println("Hello this is a static block");
   }
   public static void demo() {
      System.out.println("Contents of the static method");
   }
   public static void main(String args[]) {
      Sample.demo();
   }
}

Output

Hello this is a static block
Contents of the static method

Restrictions on static blocks and static methods

Static methods

  • You cannot access a non-static member (method or, variable) from a static context.

  • This and super cannot be used in static context.

  • The static method can access only static type data (static type instance variable).

  • You cannot override a static method. you can just hide it.

Static blocks

  • You cannot return anything from a static block.

  • You cannot invoke a static block explicitly.

  • If exception occurs in a static block you must wrap it within try-catch pair. You cannot throw it.

  • You cannot use this and super keywords inside a static block.

  • You cannot control the order of execution dynamically in case of static blocks, they will be executed in the order of their declaration.

raja
Published on 14-Oct-2019 08:16:08
Advertisements