rakesh99
rakesh99

Reputation: 1266

How is a call to static method resolved in java?

If static methods are resolved at compile time how is an object instance able to call a static method?

class StaticCall
{
    public static void main(String[] args)
    {
        String arr[]={"Class StaticCall","calls static method of class MyMainClass"};

        MyMainClass h=new MyMainClass();
        h.main(arr);         //How is an instance able to call a static method?
        System.out.println("this is StaticCall main");  
    }   

}


class MyMainClass 
{
    public static void main(String[] args){
        System.out.println(args[0]+" "+ args[1]);
    }
}

After running the StaticCall class the output is

Class StaticCall calls static method of class MyMainClass

this is StaticCall main

As static fields and methods belong to the Class object how is an instance able to call a static method? Also when is the Class object created,Is it on first access to any of it's fields or methods?

Upvotes: 2

Views: 541

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533482

How is an instance able to call a static method?

It doesn't. Try this instead

MyMainClass h = null;
h.main(arr);   

and you will see that the instance is ignored as this is exactly the same as

MyMainClass.main(arr);   

To extend your example ... if you have

class AnotherMainClass extends MyMainClass 
{
}

then all the following call the same method.

AnotherMainClass amc = null;
amc.main(args);

((AnotherMainClass) null).main(args);

AnotherMainClass.main(args);

MyMainClass mmc = null;
mmc.main(args);

((MyMainClass) null).main(args);

MyMainClass.main(args);

Upvotes: 14

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

you can call static method by classname.staticMethod and even instance.staticMethod, instance.staticMethod internally call classname.staticMethod.

Upvotes: 1

Miserable Variable
Miserable Variable

Reputation: 28752

 h.main(arr);         //How is an instance able to call a static method?

This is just a shortcut for MyMainClass.main(arr), i.e. the static type of h. The usage is often frowned upon and most IDEs will recommend you use the type instead of instance.

Since this occurs at compile time, h can be null

Upvotes: 4

Related Questions