Can the static methods be overloaded?

Can the static methods be overloaded? Yes, We can have two or more static method with same name but different input parameters as shown  in below examples. In below code we have define the two same name method with different argument list.



public static void main() {
    System.out.println("Without param static method");
}

public static void main(int i) {
    System.out.println("With param static method");
}

Can the static methods be overloaded with same parameters? No, The same two static method can't be create in single class. The complier will trough complier time error as shown in below example.


public static void main() {
    System.out.println("Without param static method");
}

public static void main() {  
    System.out.println("Without param static method");
}
 

The above code will not compile we will get Duplicate method error.

Is it possible to define two same method with different keyword or return  typeNo. Not possible to define two same method with different return type and access modifier. Example is given in below .

public static void main() {
    System.out.println("Without param static method");
}

private static int main() {
    System.out.println("With param static method");
    return 1;
}
 
The above code will not compile we will get Duplicate method error at compile time.

No comments:

Post a Comment