Home > Backend Development > PHP Tutorial > Is Overriding Interface Method Parameters with Child Interfaces a Violation of Liskov Substitution Principle?

Is Overriding Interface Method Parameters with Child Interfaces a Violation of Liskov Substitution Principle?

DDD
Release: 2024-11-06 09:08:02
Original
1079 people have browsed it

Is Overriding Interface Method Parameters with Child Interfaces a Violation of Liskov Substitution Principle?

Overriding Interface Method Parameters: A Case of Liskov Substitution Violation

In PHP, you may encounter a situation where overriding an interface method parameter with a child interface leads to an error. Consider the following code:

<code class="php">interface Engine {

    function run();
}

interface HydroEngine extends Engine {

    function run();
}

interface Car {

    function setEngine(Engine $engine);

}

interface WaterCar extends Car {

    function setEngine(HydroEngine $engine);
}</code>
Copy after login

Unfortunately, this code produces the error:

Fatal error: Declaration of WaterCar::setEngine() must be compatible with Car::setEngine(Engine $engine)
Copy after login

Reason for the Error

The error occurs because by overriding the setEngine method in the WaterCar interface, you are violating the Liskov substitution principle. This principle states that a subclass should be substitutable for its parent class without breaking the program's behavior.

The WaterCar interface, as a subclass of Car, must accept the same parameter type as the parent interface's setEngine method, which is Engine. By overriding it with HydroEngine, you are narrowing the acceptable parameter type, making WaterCar less substitutable than Car.

Solution

To resolve this issue, you must ensure that the subclasses of an interface adhere to the same parameter types as the parent interface. In this case, you should not override the setEngine method in the WaterCar interface, but instead inherit the Car interface's definition.

The above is the detailed content of Is Overriding Interface Method Parameters with Child Interfaces a Violation of Liskov Substitution Principle?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template