Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static method in Java can be accessed using object instance [duplicate]

In Java static methods are created to access it without any object instance. It makes some sense to me. But recently I came across one strange thing that, static method in Java can also be accessed through its object instance. This looks pretty wierd to me. Does anyone of you know why this feature is provided by Java? Whats the significance of allowing static methods getting accessed with as well as without instance?

like image 296
Rengasami Ramanujam Avatar asked Feb 12 '11 12:02

Rengasami Ramanujam


People also ask

Can we access static method using object in Java?

Static method in Java can be accessed using object instance [duplicate]

Can I access static method using object?

Static methods can't access instance methods and instance variables directly. They must use reference to object. And static method can't use this keyword as there is no instance for 'this' to refer to.

How can static methods be accessed?

In the static method, the method use compile-time or early binding. For this reason, we can access the static method without creating an instance. In a non-static method, the method use runtime or dynamic binding. So that we cannot access a non-static method without creating an instance.

Can I call a static method through the object reference in Java?

We can invoke a static method by using its class reference. An instance method is invoked by using the object reference. 5. We can't access instance methods and instance variables with the help of Static methods in Java.


1 Answers

A benefit of this is that it allows you to take an instance method and turn it into a static method without having to modify any existing code (other than the class) and thus allowing for backwards compatibility. I've found this useful as many times I've come across utility methods that can be made static - I can just add the static modifier and continue on my way.

like image 127
Nate W. Avatar answered Sep 30 '22 07:09

Nate W.