Static Keyword in Java – User friendly Tech help

Static means a field or an method that belongs to the class, rather than to an instance of the class.In simple terms, it means that we can call a static method/field even without creating the object of a  class to which they belongs!.We can have a static method or a static variable.
n
nWe have used this concept in our public static void main(String[] args), while using this we never created the object of main method but instead Java virtual machine can call the main method without creating a new application object.
n
nNote:- we cannot use Static with class unlike final keyword.

n

n

n

n

n

n

n

n

Static class is not possible!!

n

How to access static method/Variable

n

Syntax:-
nClassName.StaticMethod/Variable Name
n
nExample:-
nWe would be accessing the static method of class(StartURL) using StartURL.testURL();
n

nn


Code:-
npackage Java;

n

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class StartURL {
//Creating Static variable
private static WebDriver driver;
//Creating an Static Method
public static void testURL(String sURL) {
driver = new FirefoxDriver();
driver.get(sURL);
System.out.println("Inside Static Method"); } }

n

package Java;
public class MainTestCase extends StartURL{
public static void main(String[] args) {
//Accessing the Static method without
//creating class object
StartURL.testURL("http://www.uftHelp.com"); }}

n

n
nNote:- We can still access the static method or variable by using the instance object of the class, but this is not a good coding practice.In above case we could have done it using :-  

n

 public static void main(String[] args) {
//Accessing the Static method
//By creating class object
StartURL obj = new StartURL();
obj.testURL("http://www.uftHelp.com");}

n

Still Eclipse or other Java IDE’s would generate warning message :-

nn

n
Important points:-
n1.Static method is associated with a class while non static method is associated with an object.
n2.We can use Static + final to create constant value that’s attached to a class.
nExample:-

n

package Java;
public class StartURL {
//Creating Static variable
final static int noOfDays = 365;
public static void main(String[] args) {
System.out.println(noOfDays); }}

n

3.When we create different object of an class, each class contains its distinct copy of instance variable and each is stored in different memory location but incase of static variables, it is shared across the class , which occupies an fixed location in memory.So by using static keyword we are making our program memory efficient.
n4.Non static (methods, variables) can not be accessible inside static methods,meaning we can only access  static stuff Inside static methods.
nExample:-

nn

Interface in Java

Was this article helpful?
YesNo

Similar Posts