Reputation: 211
Why can't we have a static and instance method with the same name? How does Java handle a static method and how is the invocation of static methods determined by the JVM?
Upvotes: 2
Views: 1195
Reputation: 120546
The JVM spec says
2.10.2 Method Signature
The signature of a method consists of the name of the method and the number and type of formal parameters (§2.10.1) of the method. A class may not declare two methods with the same signature.
Note that modifiers (public
, static
, etc.) are not part of the signature used by the JVM to lookup a method.
There are distinct bytecode instructions for invoking static
and non-static
methods: invokestatic and invokevirtual respectively, but both expect a method signature to identify the method to invoke.
It might be possible to change the bytecode specification so that invokestatic looks for a method with the given signature and with the static
modifier, but that would require changing how Java reflection works, and break a lot of existing code. It might also break new invocation mechanisms like invokedynamic.
Upvotes: 2
Reputation: 59
static keyword represent the class members.In a class there can be following class members
Instance members represent attribute and behaviour of individual object whereas class member represents attribute behaviour of class.
Answer to your question ,it is not the case with static methods,any method u define whether it is static or instance ,u cannot initialize the another method with same name. in java any static data member and static method are loaded in class or method area.
After loading a class following instructions are performed
Any static data member or method(represents class behaviour) are invoked using name of class.
classname.Methodname(arguments if any)
class members are common to all objects hence they are available to objects of the class:the can be also invoked as:-
objectrefrence.methodname(arguments if any)
Upvotes: 2