In Java, static is a keyword used to describe how objects are managed in memory. It means that the static object belongs specifically to the class, instead of instances of that class. Variables, methods, classes can be static.
Static class:
Only the inner class can we static and it can we call without creating the parent instance.
Static classes are used to separate a nested class from its parent and remove the dependency on that parent's instance.
public class StaticTest {public static void main(String[] args) {Parent.Child.hello();}}class Parent{static class Child {public static void hello() {System.out.println("Staic child class method");}}}//Staic child class method
Static method:
public class StaticTest {static String str="Hello";public static void main(String[] args) {hello();}public static void hello() {System.out.println("Staic method : "+str);}}Static method : Hello
public class StaticTest {static String str="Hello";public static void main(String[] args) {System.out.println("Static variable call without instance of class :"+str);hello();}public static void hello() {System.out.println("Static method : "+str);}}Static variable call without instance of class :Hello Static method : Hello
Static variables and methods can be accessed from any other class, and aren't tied to the instance of that class. For instance, say you have the following class
public class StaticTest {public static void main(String[] args) {System.out.println("Static variable call without instance of class :" + StaticDemo.str);StaticDemo.hello();}}class StaticDemo {static String str = "Hello";public static void hello() {System.out.println("Static method : " + str);}}
No comments:
Post a Comment