Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is dealing with JAVA Is it permissible to define two methods in a class tha

ID: 3813532 • Letter: T

Question

This is dealing with JAVA

Is it permissible to define two methods in a class that have identical method names and parameter lists but different return value types or different modifiers?

What is wrong in the following program?

public class Test {

public static void method(int x) {

}

public static int method(int y) {

return y;

}

}

Given two method definitions,

public static double m(double x, double y)

public static double m(int x, double y)

tell which of the two methods is invoked for:

a. double z = m(4, 5);

b. double z = m(4, 5.4);

c. double z = m(4.5, 5.4);

Explanation / Answer

public class StaticMethodTest {
  
   //for the following two mmethods method(int x) it will give error , why because method overloading is only possible with different metod parameters
   //Return type of method is not part of method signature, so just changing the return type will not overload a method in Java. In fact, just changing the return type will result in compile time error as "duplicate method X in type Y. Here is a screenshot of that error in Eclipse :
   // While overloading we need to take care of method signature i.e method signature is different .

   /*
   public static void method(int x) {
   }

   public static int method(int y) {
       return y;
   }*/

   public static double m(double x, double y) {
       System.out.println("m1 "+x +" "+y);
       return 0;
   }

   public static double m(int x, double y) {
       System.out.println("m2 "+x +" "+y);
       return 0;
   }

   public static void main(String[] args) {

       double z = m(4, 5); // will be invoked of m(int x, double y)
       double z1 = m(4, 5.4); // will be invoked of m(int x, double y)
       double z2 = m(4.5, 5.4);// will be invoked of m(double x, double y)

   }

}

output :

m2 4 5.0
m2 4 5.4
m1 4.5 5.4

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote