Have a Question?

If you have any question you can ask below or enter what you are looking for!

What is the static modifier in Java?

What is static modifier in Java?
What is the static modifier in Java?
  • Inside method implementation, if you are using at-least instance variable then that method talk about a particular object hence we should declare the method as an instance method.
  • Inside method implementation, if you are not using any instance variable then this method nowhere related to a particular object. Hence we have to declare such type of method as static method irrespective of whether we are using the static variable or not.
  • Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in
    • ClassName.methodName(args)
  • For the static method, the implementation should be available whereas for abstract method implementation is not available. Hence abstract-static combination is illegal for the method.
  • Overloading concept applicable for static methods including the main method but JVM will always call String array args main method only. Other overloaded methods we have to call the normal method
package com.java4us;

class Test {
    public static void main(String args[]) {
        System.out.println("String args main method"); // String args main method
    }

    public static void main(int args[]) {
        System.out.println("Int args main method");
    }
}
  • Inheritance concept applicable for the static method also including the main method hence while executing child class if the child doesn’t contain the main method then the parent class main method will be executed. 
package com.java4us;

public class Child extends Parent {

}
class Parent {
    public static void main(String[] args) {
        System.out.println("Parent class main method");  //Parent class main method
    }
}
  • It seems overriding concept applicable for static methods but it is not overriding and its method hiding. 
package com.java4us;

public class Child extends Parent {
    public static void main(String[] args) {
        System.out.println("Child class main method");
    }
}

class Parent {
    public static void main(String[] args) {
        System.out.println("Parent class main method");
    }
}
  • We can use static variable and method when the property is common to all objects.

Leave a Reply

Your email address will not be published. Required fields are marked *