Menu
Coddy logo textTech

메서드 오버라이딩 (@Override)

Coddy Java 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 87개 중 22번째.

Method overriding을 사용하면 하위 클래스가 부모 클래스에 이미 정의된 method를 자체적으로 구현할 수 있습니다. 이를 통해 자식 클래스는 상속받은 동작을 특정 요구 사항에 맞게 사용자 지정할 수 있습니다.

method를 overriding하면 subclass 버전은 해당 subclass의 object에 대해 parent의 버전을 완전히 대체합니다. method는 parent method와 동일한 이름과 parameters를 가져야 하며, return type은 parent의 return type과 같거나 그 하위 type이어야 합니다:

public class Animal {
    public void makeSound() {
        System.out.println("Some generic sound");
    }
}

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}

public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow!");
    }
}

@Override annotation은 parent method를 overriding하려는 의도를 compiler에 알려 줍니다. 선택 사항이지만, method 이름의 철자를 실수로 잘못 입력하거나 잘못된 parameters를 사용하면 compiler가 오류를 찾아내므로 강력히 권장됩니다:

@Override
public void makeSound() { }  // 올바름 - 컴파일러가 이를 검증함

public void makesound() { }  // 오타! 오버라이딩 대신 새 메서드를 생성함

overriding된 method를 call하면, Java는 실제 object type에 속하는 버전을 실행합니다:

Dog dog = new Dog();
dog.makeSound();  // 출력: Woof!

Cat cat = new Cat();
cat.makeSound();  // 출력: Meow!

이전 레슨에서 배운 것처럼, 새로운 코드와 함께 부모의 동작도 포함하고 싶다면 오버라이드된 메서드 안에서 super.methodName()을 사용할 수 있습니다.

challenge icon

챌린지

쉬움

자체적인 특수 동작을 제공하기 위해 하위 클래스가 Parent 메서드를 재정의하는 방식을 보여 주는 알림 시스템을 만들어 보겠습니다. @Override annotation이 실수를 찾아내는 데 어떻게 도움이 되는지, 그리고 각 하위 클래스가 상속된 메서드를 어떻게 사용자 지정할 수 있는지 확인하게 됩니다.

코드를 구성하기 위해 세 개의 파일을 만듭니다.

  • Notification.java: generic 알림을 나타내는 Parent class를 만듭니다. 다음을 포함해야 합니다.
    • message(String)를 위한 private field
    • message를 accepts하는 constructor
    • message를 반환하는 getMessage() method
    • 다음을 prints하는 send() method: Sending notification: [message]
  • EmailNotification.java: Notification을 extends하고 알림이 Email을 통해 전송되는 방식을 사용자 지정하는 하위 클래스를 만듭니다.
    • recipient Email address(String)를 위한 private field
    • message와 recipient를 모두 받으며, Parent 부분에는 super(message)를 사용하는 constructor
    • @Override annotation을 사용하여 send() method를 Override하고 다음을 prints: Emailing [recipient]: [message]
  • Main.java: object 유형에 따라 동일한 method 이름이 서로 다른 behavior를 생성하는 방식을 보여 줍니다. 두 개의 inputs, 즉 message와 Email address를 받습니다. 동일한 message로 일반 Notification과 EmailNotification을 모두 Create한 다음, 각각에 대해 send()를 call하여 서로 다른 Output을 확인합니다.

두 개의 inputs를 받습니다. message(String)와 recipient Email address(String)입니다.

Output에는 두 줄이 표시되어야 합니다. 첫 번째 줄은 Parent의 send() method에서 출력되고, 두 번째 줄은 EmailNotification의 overriding 버전에서 출력됩니다. 이는 method overriding을 통해 하위 클래스가 상속된 behavior를 자체 implementation으로 대체할 수 있음을 보여 줍니다.

직접 해보기

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // 입력 읽기
        String message = scanner.nextLine();
        String recipient = scanner.nextLine();
        
        // TODO: Create a Notification object with the message
        
        // TODO: Create an EmailNotification object with the message and recipient
        
        // TODO: Call send() on the Notification object
        
        // TODO: Call send() on the EmailNotification object
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Java 컴파일러