• Yes. We can overload static methods in java.
  • Method overriding is not possible but method overloading is possible for static methods.
  • Before that lets see about method overloading in java.

Method overloading:

  •  Defining multiple methods with same name and with different arguments is known as method overloading.
  • Multiple methods with same name and different arguments so compile time itself we can tell which method is going to get executed based on method call.
  • Method overloading also known as compile time polymorphism. 

Static methods - method overloading 

  • Its always possibles static method overloading.
  • Defining multiple static methods with same name and different arguments will possible.
  • By this we can define multiple main methods in our class with different arguments but only default main method will be called by the JVM remaining methods we need to call explicitly.
  • Lets see an example java program which explains static method overloading.

  1. class StaticMethodOverloading{
  2.  
  3. public static void staticMethod(){
  4.  
  5. System.out.println("staticMethod(): Zero arguments");
  6.  
  7.  
  8. public static void staticMethod(int a){
  9.  
  10. System.out.println("staticMethod(int a): one argument");
  11.  
  12.  
  13. public static void staticMethod(String str, int x){
  14.  
  15. System.out.println("staticMethod(String str, int x): two arguments");
  16.  
  17. }
  18.  
  19. public static void main(String []args){
  20.   
  21.   StaticMethodOverloading.staticMethod();
  22.   StaticMethodOverloading.staticMethod(12);
  23.   StaticMethodOverloading.staticMethod("Static method overloading",10);
  24.  
  25. }
  26. }


 Output:

  1. staticMethod(): Zero arguments
  2. staticMethod(int a): one argument
  3. staticMethod(String str, int x): two arguments


Java Program to overload main method in java

  1. class mainMethodOverloading{
  2.  
  3. public static void main(boolean x){
  4.  
  5. System.out.println("main(boolean x) called ");
  6.  
  7.  
  8. public static void main(int x){
  9.  
  10. System.out.println("main(int x) called");
  11.  
  12.  
  13. public static void main(int a, int b){
  14.  
  15. System.out.println("main(int a, int b) called");
  16.  
  17. }
  18.  
  19. public static void main(String []args){
  20.    
  21.  
  22. System.out.println("main(String []args) called ");
  23.  
  24.   mainMethodOverloading.main(true);
  25.   mainMethodOverloading.main(10);
  26.  mainMethodOverloading.main(37,46);
  27.  
  28.  
  29. }
  30. }




 Output:

  1. main(String []args) called
  2. main(boolean x) called
  3. main(int x) called
  4. main(int a, int b) called

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu