
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Restrictions on Static Methods and Static Blocks in Java
Static Methods and Static Blocks
Static methods belong to the class and they will be loaded into 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
The following example demonstrates the usage of static blocks and static methods in Java -
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(); } }
Let us compile and run the above program, which will give the following result -
Hello this is a static block Contents of the static method
Restrictions on Static Methods
The following are the points to be noted while working with static blocks -
-
You cannot access a non-static member (method or variable) from a static context.
-
This and super cannot be used in a static context.
-
The static method can access only static type data and methods. (static type instance variable).
-
You cannot override a static method. You can just hide it.
Restrictions on Static Methods
The following are the points to be noted while working with static blocks -
-
You cannot return anything from a static block.
-
You cannot invoke a static block explicitly.
-
If an exception occurs in a static block, you must wrap it within a try-catch pair. You cannot throw it.
-
You cannot use these 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.