Search This Blog

Sunday, July 26, 2020

Method Overloading

Method Overloading:

 Method overloading is a feature that allows s to have more than one method with the same name , so as long as we use different parameters  

Example:
    we have to create a method which can do:

   a. The sum of two numbers
   b.  The sum of three numbers
   c.  The sum of four numbers

Advantages 
 1. it improves code readability.
 2. it improves code re-usability
 3. it's easier to remember one method name instead of multiple method name.
 4. it achieves  consistency in naming . One name for different methods that are commonly used.
 5. Overloaded methods gives programmers the flexibility to call  similar method with different types of data.
   
  
Each method would have parameters passed to it with the numbers to sum.



     1 inch = 2.54 centimeters
     1 foot  = 12 inch


Program:


public class MethodOverloading {
public static void main(String[] args) {

int calculateScore = calculateScore("Pankaj kumar", 70);
System.out.println("Points = " + calculateScore);
calculateScore(50);
}

public static int calculateScore(String playerName, int score) {

System.out.println("Player name : " + playerName + " score : " + score + " points ");
return score * 1000;
}

public static int calculateScore(int score) {

System.out.println("Unnamed Player name  score : " + score + " points ");
return score * 1000;
}
}

Program:



public class FeelAndInches {
public static void main(String[] args) {
calFeetAndInches(6, 0);
calFeetAndInches(7, 5);
calFeetAndInches(-10, 0);
calFeetAndInches(1, 1);
calFeetAndInches(100);
}

public static double calFeetAndInches(double feet, double inches) {
if ((feet < 0) || ((inches < 0) && (inches > 12))) {
System.out.println("Invalid feet || inches");
return -1;
}
double centimeters = (feet * 12) * 2.54;
centimeters += inches * 2.54;
System.out.println(feet + " feet " + inches + " inches " + centimeters + " centimeters ");
return centimeters;
}

public static double calFeetAndInches(double inches) {
if (inches < 0)
return -1;

double feet = (int) inches / 12;
double remaningInInches = (int) inches % 12;
System.out.println(inches + " inches is equal to " + feet + " feet and " + remaningInInches + " inches ");
return calFeetAndInches(feet, inches);
}
}

program:

public class SecondsAndMinutes {
public static void main(String[] args) {

getDurationString(65, 45);
// System.out.println(3945L);
}

public static String getDurationString(long minute, long seconds) {
if ((minute < 0) || (seconds < 0) || (seconds > 59)) {
return "Invalid input";
}
long hours = minute / 60;
long remainingMinutes = minute % 60;
return hours + " h " + remainingMinutes + " m " + seconds + " s";
}

public static String getDurationString(long seconds) {

if (seconds < 0)
return "Invalid input";
long minutes = seconds / 60;
long remainingSeconds = seconds % 60;
return getDurationString(minutes, seconds);
}

}



No comments:

Post a Comment