Method Overloading in Java Interview Questions and Answers for internship
-
What is method overloading in Java?
- Answer: Method overloading is a feature in Java that allows a class to have multiple methods with the same name but different parameters. These parameters can differ in number, type, or both. The compiler determines which method to call based on the arguments provided during the method invocation.
-
Explain the concept of compile-time polymorphism with respect to method overloading.
- Answer: Method overloading is an example of compile-time polymorphism (also known as static polymorphism). The compiler decides which overloaded method to invoke at compile time based on the method signature (name and parameters). This is in contrast to runtime polymorphism (dynamic polymorphism) where the method to be called is determined at runtime.
-
What are the rules for method overloading in Java?
- Answer: Overloaded methods must have the same name but differ in either the number of parameters, the type of parameters, or both. The return type alone cannot distinguish overloaded methods. The order of parameters matters; a change in parameter order constitutes a new method signature.
-
Can overloaded methods have different return types?
- Answer: Yes, overloaded methods can have different return types, but the parameters must be different. The compiler uses the parameter list to determine which method to call, not the return type.
-
Give an example of method overloading in Java.
- Answer: ```java class MyClass { void myMethod(int a) { System.out.println("int: " + a); } void myMethod(String s) { System.out.println("String: " + s); } void myMethod(int a, int b) { System.out.println("int, int: " + a + ", " + b); } } ```
-
What is the advantage of using method overloading?
- Answer: Method overloading improves code readability and reduces the need for multiple method names that perform similar tasks with slightly different inputs. It promotes code reusability and maintainability.
-
How does the Java compiler resolve overloaded method calls?
- Answer: The Java compiler uses a process called name mangling and examines the method signature (name and parameter types) to determine which overloaded method to call. It selects the method whose signature exactly matches the arguments passed during the method call.
-
What happens if there's an ambiguity in overloaded method calls?
- Answer: If the compiler cannot uniquely determine which overloaded method to call (e.g., due to type conversion ambiguity), it results in a compile-time error.
-
Can you overload a main method in Java?
- Answer: Yes, you can overload the `main` method in Java. However, only the method with the signature `public static void main(String[] args)` will be executed when the program is run.
Thank you for reading our blog post on 'Method Overloading in Java Interview Questions and Answers for internship'.We hope you found it informative and useful.Stay tuned for more insightful content!