Monday, June 30, 2014

Can main method be overloaded and overridden in Java?

In this example B and C have main methods, if I overload it on C my application runs the main method on B. public static void main(String args[]) is a static method and it cannot be overridden either because it belongs to the class and not to the instance, when I try to override it and execute it from class C the main method that runs is the one from C which belongs to C and it's not an overridden version of B's main method. 


package inheritance; 

public class A { 
public void ABC(){ 
System.out.println("Hello from class A"); 



package inheritance; 

public class B extends A { 
public void ABC(){ 
System.out.println("Hello from subclass B"); 
super.ABC(); 


public static void main(String[] args) { 
B s = new B(); 
s.ABC(); 



package inheritance; 

public class C extends B { 
public void ABC(){ 
System.out.println("Hello from subclass C"); 
super.ABC(); 

public static void main (String[] args){ 
C c = new C(); 
c.ABC(); 


Hello from subclass C 
Hello from subclass B 
Hello from class A

well, you can overload it, yes 
package inheritance; 

public class C extends B { 
public void ABC(){ 
System.out.println("Hello from subclass C"); 
super.ABC(); 


public static void main (String[] args){ 
C c = new C(); 
c.ABC(); 
B.main(null); 
C.main(1); 
C.main(null, null); 

public static void main(int argv){ 
System.out.println("i'm main(int argv) overloaded"); 

public static void main(String[]argv, String[]args){ 
System.out.println("i'm main(String[]argv, String[]args) overloaded"); 


Hello from subclass C 
Hello from subclass B 
Hello from class A 
Hello from subclass B 
Hello from class A 
i'm main(int argv) overloaded 
i'm main(String[]argv, String[]args) overloaded