Search Logic Blocks

Wednesday, January 29, 2020

Java: Static Methods

Static methods / class methods are those methods which are a part of the class, but they don't need any object to be created. In each program, we have used a static method main(). So, being static, we don't need to create any object to call main method. It takes only one String argument.
public static void main(String args[])
So, why we need static methods. Sometimes, we have to add common functionality to the class but is not related to data fields. As static method belongs to a class, not to the object, it can access only static variables. And static methods can call only static methods. Let's see an example of static method.

Class StaticDemo (StaticDemo.java)
public class StaticDemo {
    static String hello = "Hello";
    public static void main(String args[]) {
        sayHello1();
        StaticDemo sd = new StaticDemo();
        sd.sayHello2();
    }

    static void sayHello1 () {
        System.out.println("Say " + hello);
    }

    void sayHello2 () {
        System.out.println("Say " + hello);
    }
}
In above program, we have two methods in addition to main method - sayHello1 (static) and sayHello2 (non-static). You can see that the methods are called from main method which is a static method. Static method sayHello1 is called directly as it is static method and we don't need to create an object. But to call non-static method, we created an object of class StaticDemo and then call the method. Here is the output!!

Say Hello

Say Hello

As I mentioned above static methods are called class methods and non-static methods are called instance methods. Class methods vs Instance methods -
  • Instance methods can access both static / non-static methods and variables directly. But static methods can access only static (class) methods and static (class) variables directly.
  • Static methods don't use this keyword. As static method belongs to the class, not an object, it doesn't have any reference of an object to use this keyword.

No comments: