트랙
/
Java
Java
/
연습 문제
/
마법사와 전사 2
마법사와 전사 2

마법사와 전사 2

학습 연습 문제

소개

메서드 오버로딩

Java에서 메서드 오버로딩은 매개변수 목록만 다르다면 하나의 클래스가 같은 이름의 메서드를 여러 개 가질 수 있게 해주는 기능이에요. 컴파일 시점(또는 정적) 다형성과 관련이 있어요. 이 개념은 비슷한 작업을 하지만 입력이 다른 메서드를 만들 때 아주 중요해요.

왜 메서드를 오버로딩할까요?

메서드 오버로딩은 프로그램의 가독성을 높여줘요. 서로 다른 메서드에 같은 이름을 붙이되 매개변수를 다르게 할 수 있어요. 매개변수의 개수나 타입에 따라 그에 맞는 메서드가 호출돼요.

메서드를 오버로딩하는 방법

메서드 오버로딩의 핵심은 메서드 시그니처예요. 두 메서드는 시그니처가 다르면 서로 다른 메서드로 취급돼요. 메서드를 오버로딩하는 방법은 두 가지예요:

  1. 매개변수의 개수가 다른 경우: 이름은 같지만 매개변수의 개수가 다른 메서드를 만들 수 있어요.

    public class Display {
    
        public void show(int x) {
            System.out.println("Show with int: " + x);
        }
    
        public void show(int x, int y) {
            System.out.println("Show with two ints: " + x + ", " + y);
        }
    }
    
  2. 매개변수의 타입이 다른 경우: 이름과 매개변수의 개수는 같지만 타입이 다른 메서드를 만들 수 있어요.

    public class Display {
    
        public void show(int x) {
            System.out.println("Show with int: " + x);
        }
    
        public void show(String s) {
            System.out.println("Show with String: " + s);
        }
    }
    

기억할 점

  • 오버로딩된 메서드는 인자 목록이 달라야 해요.
  • 오버로딩된 메서드는 반환 타입도 바꿀 수 있지만, 반환 타입만 바꾸는 것은 메서드 오버로딩이 되지 않아요.
  • 메서드는 같은 클래스 안에서도, 하위 클래스에서도 오버로딩할 수 있어요.

이번 개념에서는 Java에서의 메서드 오버로딩에 대한 다양한 예제와 미묘한 차이점을 살펴볼 거예요.

지침

이 연습 문제에서 여러분은 가장 친한 친구들과 "Wizard and Warriors"라는 롤플레잉 게임을 하고 있어요. 게임 마스터는 바로 여러분이에요. 게임 마스터는 플레이어들에게 게임 세계를 생생하게 느낄 수 있게 만들어 주는 역할을 맡은 사람이에요. 이때 중요한 것 중 하나는 플레이어들에게 게임을 설명하는 거예요. 캐릭터의 상태는 어떤지, 방문하는 마을은 어떻게 생겼는지 등등이요.

여러분에게는 플레이어들에게 게임의 여러 부분을 설명하는 다섯 가지 과제가 있어요.

1. 캐릭터를 설명해요

각 캐릭터는 클래스, 레벨, 체력을 가지고 있고, 다음과 같이 설명돼요: "You're a level <LEVEL> <CLASS> with <HIT_POINTS> hit points.". Character를 유일한 매개변수로 받아 설명을 반환하는 GameMaster.describe 메서드를 구현해요.

Character character = new Character();
character.setCharacterClass("Wizard");
character.setLevel(4);
character.setHitPoints(28);

new GameMaster().describe(character);
// => "You're a level 4 Wizard with 28 hit points."

2. 목적지를 설명해요

각 목적지는 이름과 주민 수를 가지고 있고, 다음과 같이 설명돼요: "You've arrived at <NAME>, which has <INHABITANTS> inhabitants.". Destination을 유일한 매개변수로 받아 설명을 반환하는 GameMaster.describe 메서드를 구현해요.

Destination destination = new Destination();
destination.setName("Muros");
destination.setInhabitants(732);

new GameMaster().describe(destination);
// => "You've arrived at Muros, which has 732 inhabitants."

3. 이동 방법을 설명해요

캐릭터는 두 가지 방법 중 하나로 목적지까지 이동할 수 있어요:

  • 걷기, 다음과 같이 설명돼요: "You're traveling to your destination by walking."
  • 말을 타고, 다음과 같이 설명돼요: "You're traveling to your destination on horseback."

TravelMethod를 유일한 매개변수로 받아 설명을 반환하는 GameMaster.describe 메서드를 구현해요.

new GameMaster().describe(TravelMethod.HORSEBACK);
// => "You're traveling to your destination on horseback."

4. 목적지로 이동하는 캐릭터를 설명해요

캐릭터가 목적지로 이동할 때는 각각의 설명을 조합해서 나타내요: "<CHARACTER> <TRAVEL_METHOD> <DESTINATION>". Character, Destination, TravelMethod를 매개변수로 받아 설명을 반환하는 GameMaster.describe 메서드를 구현해요.

Character character = new Character();
character.setCharacterClass("Wizard");
character.setLevel(4);
character.setHitPoints(28);

Destination destination = new Destination();
destination.setName("Muros");
destination.setInhabitants(732);

new GameMaster().describe(character, destination, TravelMethod.HORSEBACK);
// => "You're a level 4 Wizard with 28 hit points. You're traveling to your destination on horseback. You've arrived at Muros, which has 732 inhabitants."

5. 이동 방법을 명시하지 않고 목적지로 이동하는 캐릭터를 설명해요

대부분의 경우 캐릭터는 걷기로 목적지까지 이동해요. 편의를 위해 플레이어는 이동 방법을 생략할 수 있고, 이 경우 걷기가 이동 방법으로 간주돼요. Character와 Destination을 매개변수로 받아 설명을 반환하는 GameMaster.describe 메서드를 구현해요.

Character character = new Character();
character.setCharacterClass("Wizard");
character.setLevel(4);
character.setHitPoints(28);

Destination destination = new Destination();
destination.setName("Muros");
destination.setInhabitants(732);

new GameMaster().describe(character, destination);
// => "You're a level 4 Wizard with 28 hit points. You're traveling to your destination by walking. You've arrived at Muros, which has 732 inhabitants."
GitHub에서 편집 링크가 새 창이나 탭에서 열려요
Java Exercism

마법사와 전사 2 문제를 시작해 볼 준비가 됐나요?

Exercism에 가입하고 Java 트랙을 개념 26개연습 문제 158개, 그리고 실제 사람의 멘토링과 함께 배우고 익혀 보세요. 모두 무료예요.