V
V
vasx32020-12-04 16:38:20
OOP
vasx3, 2020-12-04 16:38:20

How is the implementation of an interface chosen?

Tell me, how is the choice of interface implementation when one interface is implemented by several classes?

Let's say we have a machine interface

interface ICar {
  start();
  stop();
}

It is implemented by several classes
class Sportcar implements ICar {
  start() {
     /**/
  }
  stop() {
    /**/
  }
  //nitro() {
  //  /**/
  //}
}
class Bus implements ICar {
  start() {
     /**/
  }
  stop() {
    /**/
  }
  //openDoor() {
  //  /**/
  //}
}

In the final method, you can get an object by interface type and it will work
function startCar(ICar $car) {
  $car->start();

But how is the choice of the class that is ultimately returned in the method?
(not relevant) How can I be sure that I will get back an object of the Bus class, and that it will contain the openDoor method?

I'm trying to understand the need for abstractions.
Everywhere it is said that it is necessary to separate individual parts of the application, use classes not directly, but through interfaces to remove dependencies.
But I cannot understand how, in the case of using interfaces, I can be sure that the data received is consistent.
It turns out somehow not transparent.

upd.
Roughly speaking, it is not clear to me in which case, when using the ICar $car variable, a Sportcar object will be obtained , and in which Bus object?
Or is it better to immediately get a variable like Sportcar or Bus , and use the interface only for standardization?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Grigory, 2020-12-04
@Griglapidus

An interface should not be treated as a data type. You are not calling an interface method, you are calling a method on a class that inherits from the interface. You do not create an object of type ICar. You create an object of type Sportcar and you access the object of type Sportcar through the ICar interface methods.

S
soloveid, 2020-12-04
@soloveid

The runtime knows which implementation (Bus or Sportcar) is behind ICar and it
calls the methods of this class.
This is so because at the beginning of the memory where this object is located, its type is indicated (Bus or Sportcar).

upd.
Roughly speaking, it is not clear to me in which case, when using the ICar $car variable, the Sportcar object will be obtained, and in which Bus object?
Or is it better to immediately get a variable like Sportcar or Bus, and use the interface only for standardization?

It's not entirely clear why you need to know this? That's what interfaces are for. If you suddenly want to mean exactly which type and in this case execute some separate code, then this is not good.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question