What is Static and non Static Method in Java

-- Leave a Comment
The Static Keyword means that the variables or methods are shared between all instances of that class as it belongs to the type, not the actual objects themselves.

So you can access static method of a class without it's object. For non static methods, every methods are associated with a object so you should call those non static method using your object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Test {
    private int countObj;
    public Test() {
        countObj++;
    }
    public static void main(String args[]) {
        System.out.println("Hello, I am static.");
        aStatic();
        System.out.println("Calling non Static Method Directly.");
        nonStatic(); // not allowed
        Test aTest = new Test;
        System.out.println("Calling non Static Method via from object");
        aTest.nonStatic(); // Allowed 
    }
    static void aStatic() {
        System.out.println("Inside aStatic");
    }
    void nonStatic() {
        System.out.println("This is non Static Method.")
    }
}

We can call static methods from any methods of type class with it's name only, where as we need to specify the class to call from other class methods. Test.aStatic();
the countObj is a static variable so it is same for all the instance of the class. It will count the object created.
Thank you!

Hello This is Sagar Devkota. Studying Bachelor of Software Engineering at Pokhara University, NCIT. Open Source Enthusiastic.

0 comments:

Post a Comment