- 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.
- class StaticMethodOverloading{
- public static void staticMethod(){
- System.out.println("staticMethod(): Zero arguments");
- }
- public static void staticMethod(int a){
- System.out.println("staticMethod(int a): one argument");
- }
- public static void staticMethod(String str, int x){
- System.out.println("staticMethod(String str, int x): two arguments");
- }
- public static void main(String []args){
- StaticMethodOverloading.staticMethod();
- StaticMethodOverloading.staticMethod(12);
- StaticMethodOverloading.staticMethod("Static method overloading",10);
- }
- }
Output:
- staticMethod(): Zero arguments
- staticMethod(int a): one argument
- staticMethod(String str, int x): two arguments
Java Program to overload main method in java
- class mainMethodOverloading{
- public static void main(boolean x){
- System.out.println("main(boolean x) called ");
- }
- public static void main(int x){
- System.out.println("main(int x) called");
- }
- public static void main(int a, int b){
- System.out.println("main(int a, int b) called");
- }
- public static void main(String []args){
- System.out.println("main(String []args) called ");
- mainMethodOverloading.main(true);
- mainMethodOverloading.main(10);
- mainMethodOverloading.main(37,46);
- }
- }
Output:
- main(String []args) called
- main(boolean x) called
- main(int x) called
- main(int a, int b) called
No comments