What is static variable static method and static class in Java?

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
In above code we have define static class inside the parent class and static Child class hello() method we can call without creating the instance of Parent class.

Static method:

In Java, a static method is a method that belongs to a class rather than an instance of a class. Static methods have access to class variables (static variables) without using the class's object (instance). Non static variable can't we used in static method.

Static method can be accessed from any other class, and no need to instance of that class. 

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
In above code we have created one hello() static method and calling without creating the instance of class.

Note: If method is static then it can't be override. read more

Static variable: Static variables, by contrast, are variables associated with a class itself, rather than a particular instance of that class.

Static variables can be accessed from any other class, and no need to instance of that class. 

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