본문 바로가기
프로그래밍언어/Java

[Java] : method overriding

by 오주현 2022. 1. 17.
반응형

메서드 오버라이딩

메서드 오버라이딩은 상위 클래스의 메서드를 하위 클래스에서 재정의 하는 것을 말한다.

예시 코드

class ToyPenSetting {
    String color = "Red";

    void changeColor(String color) {
        this.color = color;
        System.out.println("장난감 연필의 색상 (부모 클래스) => " + this.color);
    }
}

ToyPenSetting 클래스는 부모 클래스이다.

펜의 색상을 Red로 초기화 시켜놓고 changeColor라는 색상을 바꿔주는 메서드를 만들어 줬다.

class TestPen1 extends ToyPenSetting{
    void changeColor(String color) {
        this.color = color;
        if (color == "Blue") {
            this.color = "Black";
        }
        System.out.println("장난감 연필의 색상 (자식 클래스) => " + this.color);
    }
}

TestPen1 클래스는 첫 번째 자식 클래스이다.

부모 클래스인 ToyPenSetting를 상속 받았고 changeColor 메서드를 살짝 변형을 줘 재정의 해줬다.

Blue 색상이 파라미터 값으로 들어오면 Black 색상으로 바뀌도록 코드를 만들어줬다.

class TestPen2 extends ToyPenSetting{

}

TestPen2 클래스는 두 번째 자식 클래스이다.

부모 클래스인 ToyPenSetting를 그대로 상속 받았고 TestPen1과 달리 따로 재정의하지 않았다.

파라미터 값으로 색상이 들어오면 바로 부모 클래스인 ToyPenSetting의 changeColor 메서드를 변형 없이 실행할 것이다.

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

        TestPen1 testPen1 = new TestPen1();
        TestPen2 testPen2 = new TestPen2();

        System.out.print("TestPen2 => ");
        testPen2.changeColor("Blue");

        System.out.print("TestPen1 => ");
        testPen1.changeColor("Blue");
    }
}

ToyPen 클래스에서 TestPen1과 TestPen2의 인스턴스를 생성해 줬다.

그리고 각각 Blue 값을 파라미터 값으로 넣어줬고 실행을 해보면

TestPen2는 따로 재정의한 메서드가 없기 때문에 입력한 Blue 파라미터를 그대로 changeColor로 넘겨 색상을 변경했고, TestPen1은 Blue의 값이 들어올 경우 Black 값으로 바뀌게끔 if문을 넣어 재정의해줬기 때문에 그에 맞게 Black가 출력이 되는 것을 볼 수 있다.

만약 여기서 자식 클래스에서 부모 클래스의 메서드를 강제 호출하려면 super() 메서드를 사용하면 된다.

class TestPen1 extends ToyPenSetting{
    void changeColor(String color) {
        super.changeColor(color);
        this.color = color;
        if (color == "Blue") {
            this.color = "Black";
        }
        System.out.println("장난감 연필의 색상 (자식 클래스) => " + this.color);
    }
}

super.chageColor(color);을 넣어줬고 부모 클래스가 호출이 된다.

이 상태로 출력을 해보면

이렇게 Blue값이 들어간 부모 클래스가 호출이 되고 자식 클래스는 부모 클래스의 값을 받고 난 뒤 if문을 통해 Black 색상으로 바뀌는 것을 확인할 수 있다.

반응형

댓글