Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any difference between "invoking a static method with class name" and "invoking a static method with an object" in java?

Tags:

java

static

in java we are able to "invoke a static method with class name" and also "invoke a static method with an object" what is the difference between "invoking a static method with class name" and "invoking a static method with an object" in java?

like image 855
madan Avatar asked Jul 10 '13 07:07

madan


2 Answers

There is no difference but the recommendation is to call the static methods in a staic way i.e. using the ClassName. Generally static analayzers will report an error if you don't do so.

An important thing to understand here is that static method are stateless and hence calling them with an instance is confusing for someone reading your code. Because no matter what instance you use to call the static method, result will remain the same. This is because a static method belongs to a class but not to an object.

like image 63
Juned Ahsan Avatar answered Sep 22 '22 13:09

Juned Ahsan


There is no difference at all. But since static methods are at the class level, you can access them using the class name. Though invoking them using class object is possible, it creates a confusion. Why would you like to invoke them for every object if its value is going to be the same?

like image 20
paary Avatar answered Sep 18 '22 13:09

paary