ZohebSiddiqui
ZohebSiddiqui

Reputation: 211

Invocation of static methods in the Java virtual machine

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

Answers (2)

Mike Samuel
Mike Samuel

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

Dikshant
Dikshant

Reputation: 59

static keyword represent the class members.In a class there can be following class members

  1. static data members
  2. static block
  3. static methods.

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

  1. static data members (if define ) are created in class area.
  2. static bloc (if define )is executed.

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

Related Questions