In this tutorial, we will learn What Does The ‘Static’ Keyword Do In A Class? in java, the Static keyword is generally used for memory management where the keyword is used to share the same variable or method of a given class in java.
Static Keyword
It is a non-access modifier in java where we can use this keyword for variables, classes, blocks, and Methods and every time we have to use the keyword ‘Static’ before it to make it static. In all cases, static keyword plays different roles.
Static Class
A static class can be made static only in the nested class which means we can not declare the class as static if it is top-class which means it is only possible in the case of inheritance. And static class need not refer to the superclass. Moreover, a static class can not access non-static members of the Outer class.
public class ABC { private static String str = "Prakhar Yadav"; // Static class static class MyNestedClass { // non-static method public void disp(){ System.out.println(str); } } public static void main(String args[]) { ABC.MyNestedClass obj = new ABC.MyNestedClass(); obj.disp(); } }
As we can see how Class ABC is an outer Class that has mynextedClass as a nested or inner class and which can be static. And the output of this program will be “Prakhar Yadav”.
Static Variable
Static Variables are used to keep the information and are used at every instant of class. They are the variable to get the common property of an object of the class.
Let’s understand more with the help of examples.
class sv { static String name = "abc"; } public class staticvariable { static int t; public static void main(String[] args) { System.out.println("static variable is - "+t); System.out.println(sv.name); t=100; System.out.println(t); } }
Learn More about Static words used in different situations. Static keyword
And also visit at JAVA TUTORIALS for learning more about java and different tutorials about java.