Wednesday, 28 August 2013

Difference between Static and Dynamic binding in java

Difference between Static and Dynamic binding in java

1) Static binding in Java occurs during Compile time while Dynamic binding occurs 
    during Runtime.

2) private, final and static methods and variables uses static binding and bonded by compiler while virtual methods are bonded during runtime based upon runtime object.

3) Static binding uses Type(Class in Java)  information for binding while Dynamic binding uses Object to resolve binding.

3) Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.



Can we overload and override main method in java

Can we overload main() method in java:
Yes we can !!

But only public static void main(String[] args) will be used when your class is launched by JVM , as :- 


But it will always print 
main(String[] args)

public class Test {
    public static void main(String[] args) {
        System.out.println("main(String[] args)");
    }

    public static void main(String arg1) {
        System.out.println("main(String arg1)");
    }

    public static void main(String arg1, String arg2) {
        System.out.println("main(String arg1, String arg2)");
    }
}


We can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied. 
Note that you can use a varargs signature, as that's equivalent from a JVM standpoint: -
public static void main(String... args)


Can we override the main method in java

No!
main is a static method, and is thus not polymorphic. You may hide it be defining another static main method in a subclass, though.