It is really difficult to distinguish interfaces from abstract classes. They are very similar to each other, and there is no defined logic for methods. They are all intended or inherited for subclasses. To distinguish the two, just remember one sentence:Interfaces are standards and classes are implementations.The purpose of an interface is to define a specification that everyone complies.
That is to say, the objective can clearly understand the region-specific interface and abstract class. So I still have doubts, since there is an excuse, why must there be an abstract class?
In addition, we want to define a class named Animal, which has two subsets: Dog and Cattle. Both of them have two methods: run () and speak.
Assume that the "run" of Dog and Cattle are the same, so the run () method has the same business logic, while the "speak" method is different, therefore, the business logic of the speak () method is different. Moreover, there is an IAnimal interface that requires the two methods, which means that the Animal class must implement these two methods. Similarly, do Dog and Cattle subclasses must also have these two methods, we can define it as follows:
Copy codeThe Code is as follows:
<? Php
Interface IAnimal {
Public function run ();
Public function speak ();
}
Class Animal implements IAnimal {
Public function run (){
// Some identical run logic can be added here
Return "same run <br/> ";
}
Public function speak (){
// Some identical speak logic can be added here
Return "same speak <br/> ";
}
}
Class Dog extends Animal {
Public function speak (){
// Some Dog logic can be added here
Return "Dog speak <br/> ";
}
}
Class Cattle extends Animal {
Public function speak (){
// Some Cattle logic can be added here
Return "Cattle speak <br/> ";
}
}
$ ODog = new Dog ();
Echo ($ oDog-> run ());
Echo ($ oDog-> speak ());
$ OCattle = new Cattle ();
Echo ($ oCattle-> run ());
Echo ($ oCattle-> speak ());
?>