백엔드 기술/Java

메서드 오버라이딩 VS 오버로딩

DvdHan 2023. 4. 15. 21:54

1. 오버 라이딩 (Overriding)
상위 클래스로부터 상속받은 메서드
동일한 메서드 이름이지만 메서드 바디를 필요에 따라 재정의 하는 것.

[조건]
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();
    }
}

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

 

2. 오버 로딩 (Overloading)
하나의 클래스 안에 같은 이름의 메서드를 매개변수를 다르게하여 여러 개 정의하는 것.

```java
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();
    }
}

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

[조건]
1. 같은 이름의 메서드명을 사용해야 한다.
2. 매개변수의 개수나 타입이 각 각 다르게 정의되어야 한다.
3. 반환타입 관계 없음.

[장점]
하나의 메서드로 여러 경우의 수를 해결할 수 있다.