0

use of static keyword in java

use of static in java

Normally, a class member must be accessed only with an object of its class.In java it is possible to create a member,precede its declaration with the keyword static.When a member is declared static,it can be accessed before any objects of its class are created, and without reference to any object.
When objects of static class are declared,no copy of a static variable is made.Instead,all instance of the class share the same static variable.

Rules for the method declared as static

  • They can only call other static methods.
  • They must only access static data.
  • They cannot refer to this or super in any way.

For example

Main() is the most common example of static.main() is declared as static because it must be called before any object exist

output

The Staticuse class is loaded,all the static statements are run,first a is set to 3 then the static block executes,which prints a message and then initializes b to a*4 or 12 Then main() is called.which calls cal(),passing 42 to x.The three println() statement refer to the two static variable a and b.

Outside of the class static methods and variables can be used independently of any object.to do so we have to specify the name of their class followed by the dot operator

Output

Pravesh Kumar

Leave a Reply

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