Static and non-Static Method in java
Advertisements
Difference between Static and non-static method in Java
In case of non-static method memory is allocated multiple time whenever method is calling. But memory for static method is allocated only once at the time of class loading. Method of a class can be declared in two different ways
- Non-static methods
- Static methods
Difference between non-static and static Method
Non-Static method | Static method | |
---|---|---|
1 | These method never be preceded by static keyword Example: void fun1() { ...... ...... } | These method always preceded by static keyword Example: static void fun2() { ...... ...... } |
2 | Memory is allocated multiple time whenever method is calling. | Memory is allocated only once at the time of class loading. |
3 | It is specific to an object so that these are also known as instance method. | These are common to every object so that it is also known as member method or class method. |
4 | These methods always access with object reference Syntax: Objref.methodname(); | These property always access with class reference Syntax: className.methodname(); |
5 | If any method wants to be execute multiple time that can be declare as non static. | If any method wants to be execute only once in the program that can be declare as static . |
Note: In some cases static methods not only can access with class reference but also can access with object reference.
Example of Static and non-Static Method
Example
class A { void fun1() { System.out.println("Hello I am Non-Static"); } static void fun2() { System.out.println("Hello I am Static"); } } class Person { public static void main(String args[]) { A oa=new A(); oa.fun1(); // non static method A.fun2(); // static method } }
Output
Hello I am Non-Static Hello I am Static
Following table represent how the static and non-static properties are accessed in the different static or non-static method of same class or other class.
Program to accessing static and non-static properties.
Example
class A { int y; void f2() { System.out.println("Hello f2()"); } } class B { int z; void f3() { System.out.println("Hello f3()"); A a1=new A(); a1.f2(); } } class Sdemo { static int x; static void f1() { System.out.println("Hello f1()"); } public static void main(String[] args) { x=10; System.out.println("x="+x); f1(); System.out.println("Hello main"); B b1=new B(); b1.f3(); } }
Google Advertisment