Java

Method Overloading

Alledy 2019. 3. 14. 21:07
  • Method Overloading

    Same named method and different number of parameters.

    • 예제1 - 숫자들의 sum 구하기

      • 안 좋은 예
      public static int sumTwoNum(int a, int b) {
          return a + b;
      }
      
      public static int sumThreeNum(int a, int b, int c) {
          return a + b + c;
      }
      
      public static int sumFourNum(int a, int b, int c, int d) {
          return a + b + c + d;
      }
      

      메소드 이름이 다 다르기 때문에 복잡하고 기억하기 어렵다.

       

      • Overloading
      public static int sum(int a, int b) {
          return a + b;
      }
      
      public static int sum(int a, int b, int c) {
          return a + b + c;
      }
      
      public static int sum(int a, int b, int c, int d) {
          return a + b + c + d;
      }
      

      Overloading하면 읽기 쉽고 기억하기 훨씬 쉽다.

     

    • 예제2
    package com.Hazel;
    
    public class Main {
    
        public static void main(String[] args) {
            calcFeetAndInchesToCentimeters(50);
        }
    
        public static double calcFeetAndInchesToCentimeters(double feet, double inches) {
            if(feet < 0 || inches < 0 || inches > 12) {
                return -1;
            }
    
            double centimeters = feet * 12 * 2.54;
            centimeters += inches * 2.54;
            System.out.println(feet + " feet and " + inches + " inches = " + centimeters + " centimeters" );
            return centimeters;
        }
    
        public static double calcFeetAndInchesToCentimeters(double inches) {
            if(inches < 0) {
                return -1;
            }
            double feet = (int) inches / 12;
            double remain =  inches % 12;
            System.out.println(inches + " is equal to " +  feet + " feet and " + remain + " inches" );
            return calcFeetAndInchesToCentimeters(feet, remain);
        }
    
    }