Can a static method access non static property in java? The simple answer is “No”. But there is an indirect method to do this. Consider the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/** * @author Hafiz Muhammad Umer */ public class StatVsNonStat { public int i=0; public static void change(StatVsNonStat o) { o.i=100; } public static void main(String[] args) { StatVsNonStat obj= new StatVsNonStat(); System.out.println(obj.i); change (obj); System.out.println(obj.i); } } |
Output:
0 100
Explanation:
- The line 12 creates an object. We can not access non static property without having the instance of a class.
- The line 14 passes the object to a static method. The static method will change the non-static variable i which actually belongs to an object.
Like us on facebook fb.com/JavaWithUmer