java - Accessing static method through an object instance -
i have learnt if wish call static method of class have write class name while calling static method. in below program, created object of employee class inside employee_impl class , using object, still able access count
method. why allowing me use count
method through object if static
methods accessed using class name? mean static methods can accessed using objects class name, both?
employee.java
public class employee{ static int counter = 0; static int count(){ counter++; return counter; } }
employee_impl.java
class employee_impl public static void main(string args[]){ employee obj = new employee(); system.out.println(obj.count()); system.out.println(employee.count()); system.out.println(obj.count()); } }
output
1 2 3
compiler automatically substitutes call call class name of variable (not of it's value!). note, if object null, it work, no nullpointerexception
thrown.
Comments
Post a Comment