티스토리 뷰

728x90
반응형

메서드 오버라이딩은 상위 클래스로부터 상속받은 메서드와 동일한 이름의 메서드를 재정의하는 것을 말한다.

 

Override 자체가 덮어쓰다는 뜻이니 기능을 유추해볼 수 있겠다.

 

간단한 예를 들면 다음과 같다.

class Vehicle {
    void run() {
        System.out.println("Vehicle is running");
    }
}

public class Bike extends Vehicle { // Vehicle 클래스 상속
    void run() {
        System.out.println("Bike is running"); // 메서드 오버라이딩
    }

    public static void main(String[] args) {
        Bike bike = new Bike();
        bike.run();
    }
}

// 출력 결과
"Bike is running"

위의 예시는 Bike 클래스가 Vehicle 클래스를 상속받아 run() 메서드를 오버라이딩 하는 것을 보여주고 있다.

 

상위 클래스로부터 상속받은 run()메서드를 자신에 맞게 변경하는 것이라고 할 수도 있겠다.

 

메서드 오버라이딩은 다음의 세 가지 조건을 만족시켜야 한다.

 

  1. 메서드의 선언부(메서드 이름, 매개변수, 반환 타입)가 상위 클래스의 그것과 일치해야 한다.
  2. 접근 제어자의 범위가 상위 클래스의 메서드보다 넓거나 같아야 한다.
  3. 예외는 상위 클래스의 메서드보다 많이 선언할 수 없다.

위의 예를 조금 더 확장시켜, 오버라이딩을 사용하는 이유에 대해서 살펴보자.

public class Main {
    public static void main(String[] args) {
        Bike bike = new Bike(); // 각각의 타입으로 선언 + 각각의 타입으로 객체 생성
        Car car = new Car();
        MotorBike motorBike = new MotorBike();
        
	bike.run();
        car.run();
        motorBike.run();

	Vehicle bike2 = new Bike(); // 상위 클래스 타입으로 선언 + 각각 타입으로 객체 생성
        Vehicle car2 = new Car();
        Vehicle motorBike2 = new MotorBike();

        bike2.run();
        car2.run();
        motorBike2.run();
    }
}

class Vehicle {
    void run() {
        System.out.println("Vehicle is running");
    }
}

class Bike extends Vehicle {
    void run() {
        System.out.println("Bike is running");
    }
}

class Car extends Vehicle {
    void run() {
        System.out.println("Car is running");
    }
}

class MotorBike extends Vehicle {
    void run() {
        System.out.println("MotorBike is running");
    }
}

// 출력 결과
Bike is running
Car is running
MotorBike is running
Bike is running
Car is running
MotorBike is running

처음의 예보다 늘어난 3개의 클래스(Bike, Car, MotorBike)가 각각 Vehicle로부터 상속을 받아

 

run() 메서드를 오버라이딩 하는 것을 볼 수 있다.

 

각각 객체의 run()메서드를 실행하면 객체에 맞는 메시지가 프린트됨을 확인할 수 있다.

 

조금 더 나아가, 다형적 표현을 사용해 각 객체를 같은 상위 클래스 타입으로 선언해도 결과는 같다는 것도 확인할 수 있는데,

 

이런 경우 모든 객체를 간편하게 배열로 관리할 수 있다는 장점이 있다.

Vehicle[] vehicles = new Vehicle[] {new Bike(), new Car(), new MotorBike()};
for (Vehicle vehicle : vehicles) {
		vehicle.run();
}

지금 공부하는 동안은 잘 와닿지 않지만, 확실히 코드가 간결해진 것만은 알 수 있었다.

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
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
글 보관함