Selenium and Java

Wednesday, 24 June 2015

Java- Static Keyword

Java- Static Keyword


The static keyword can be used in 3 scenarios:

  • static variables
  • static methods
  • static blocks of code

1. Static Variable :

When a variable is declared with the keyword “static”, its called a “class variable”. All instances share the same copy of the variable. A class variable can be accessed directly with the class, without the need to create a instance.

Without the “static” keyword, it’s called instance variable, and each instance of the class has its own copy of the variable.

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.<variable-name>
















2. Static Method:

Any method defined as Static can be called without creating an object of class. The best example is main method , as at the start of execution no object created so main method is defined as Static.A
static method belongs to class rather than an object of the class

Calling Static Methods

Invoke static methods using the name of the class followed by dot (.), then the name of the method:
classname.staticMethodName(args,...)

There are two main restrictions for the static method. They are:
  1. The static method can not use non static data member or call non-static method directly.
  2. this and super cannot be used in static context.

No comments:

Post a Comment