티스토리 뷰

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);
        }
    
    }
    

     

 

'Java' 카테고리의 다른 글

자바의 특징, 변수 등  (0) 2019.04.23
Switch  (0) 2019.03.18
Coding exercise - if else if문  (0) 2019.03.14
Expression, DRY, Return  (0) 2019.03.12
Data Types  (0) 2019.03.11
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함