Study and learn Interview MCQ Questions and Answers on Java Method Overloading. Attend job interviews easily with these Multiple Choice Questions. You can print these Questions in default mode to conduct exams directly. You can download these MCQs in PDF format by Choosing Print Option first and Save as PDF option next using any Web Browser.
Go through Java Theory Notes on Method Overloading before reading these objective questions.
public class MethodOverloading1 { void show(int a, char b) { System.out.println("KING KONG"); } void show(char a, int b) { System.out.println("JIM JAM"); } public static void main(String[] args) { MethodOverloading1 m = new MethodOverloading1(); m.show(10, 'A'); m.show('B', 10); } }
JIM JAM JIM JAM
KING KONG KING KONG
KING KONG JIM JAM
Method signatures are clearly different. So both methods work.
public class MethodOverloading2 { int info() { System.out.println("PLANE"); return 0; } void info() { System.out.println("AIRPORT"); } public static void main(String[] args) { MethodOverloading2 m = new MethodOverloading2(); int a = m.info(); } }
Both methods with the same name "info" do not overload successfully as the return types are different (void and int).
class Wood{ } class SubWood extends Wood{ } public class MethodOverloading3 { Wood display(int a) { System.out.println("PINE"); return new Wood(); } SubWood display() { System.out.println("TEAK"); return new SubWood(); } public static void main(String[] args) { MethodOverloading3 m = new MethodOverloading3(); m.display(); } }
Return types for the method display() are Wood and SubWood. As these types are of superclass-subclass, it is a valid method overloading.
class Rabbit{ } class WildRabbit extends Rabbit{ } public class MethodOverloading4 { Rabbit jump() { System.out.println("Rabbit Jump"); return new Rabbit(); } WildRabbit jump() { System.out.println("Wild Rabbit Jump"); return new WildRabbit(); } public static void main(String[] args) { MethodOverloading4 obj = new MethodOverloading4(); obj.jump(); } }
The above program does not overload the method jump() properly as the argument list is not distinct. So the compiler reports "duplicate method error".
Notice that static methods can be overloaded in Java without any compiler error. So, Math.abs() works out of the box with different type arguments.
public class MyAbs { static int abs(int a) { return a<0?-a:a; } static float abs(float b) { return b<0?-b:b; } static double abs(double c) { return c<0?-c:c; } public static void main(String[] args) { int a=-10; float b=-4.56f; double c=-10.123; System.out.println(MyAbs.abs(a) + ", " + MyAbs.abs(b) + ", " + MyAbs.abs(c)); } }
The above program demonstrates the usage of Overloaded methods. "abs" function returns the absolute value of the input.