Interfaces allow you to create code which defines the methods of classes that implement it. You cannot however add any code to those methods.
Abstract classes allow you to do the same thing, along with adding code to the method.
Now if you can achieve the same goal with abstract classes, why do we even need the concept of interfaces?
I've been told that it has to do with OO theory from C++ to Java, which is what PHP's OO stuff is based on. Is the concept useful in Java but not in PHP? Is it just a way to keep from having placeholders littered in the abstract class? Am I missing something?
The entire point of interfaces is to give you the flexibility to have your class be forced to implement multiple interfaces, but still not allow multiple inheritance. The issues with inheriting from multiple classes are many and varied and the wikipedia page on it sums them up pretty well.
Interfaces are a compromise. Most of the problems with multiple inheritance don't apply to abstract base classes, so most modern languages these days disable multiple inheritance yet call abstract base classes interfaces and allows a class to "implement" as many of those as they want.
The concept is useful all around in object oriented programming. To me I think of an interface as a contract. So long my class and your class agree on this method signature contract we can "interface". As for abstract classes those I see as more of base classes that stub out some methods and I need to fill in the details.
Why would you need an interface, if there are already abstract classes?
To prevent multiple inheritance (can cause multiple known problems).
One of such problems:
The "diamond problem" (sometimes referred to as the "deadly diamond of
death") is an ambiguity that arises when two classes B and C inherit
from A and class D inherits from both B and C. If there is a method
in A that B and C have overridden, and D does not override it, then
which version of the method does D inherit: that of B, or that of C?
Source: https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem
Why/When to use an interface?
An example... All cars in the world have the same interface (methods)... AccelerationPedalIsOnTheRight(), BrakePedalISOnTheLeft(). Imagine that each car brand would have these "methods" different from another brand. BMW would have The brakes on the right side, and Honda would have brakes on the left side of the wheel. People would have to learn how these "methods" work every time they would buy a different brand of car. That's why it's a good idea to have the same interface in multiple "places."
What does an interface do for you (why would someone even use one)?
An interface prevents you from making "mistakes" (it assures you that all classes which implement a specific interface, will all have the methods which are in the interface).
// Methods inside this interface must be implemented in all classes which implement this interface.
interface IPersonService
{
public function Create($personObject);
}
class MySqlPerson implements IPersonService
{
public function Create($personObject)
{
// Create a new person in MySql database.
}
}
class MongoPerson implements IPersonService
{
public function Create($personObject)
{
// Mongo database creates a new person differently then MySQL does. But the code outside of this method doesn't care how a person will be added to the database, all it has to know is that the method Create() has 1 parameter (the person object).
}
}
This way, the Create() method will always be used the same way. It doesn't matter if we are using the MySqlPerson class or the MongoPerson class. The way how we are using a method stays the same (the interface stays the same).
For example, it will be used like this (everywhere in our code):
new MySqlPerson()->Create($personObject);
new MongoPerson()->Create($personObject);
This way, something like this can't happen:
new MySqlPerson()->Create($personObject)
new MongoPerson()->Create($personsName, $personsAge);
It's much easier to remember one interface and use the same one everywhere, than multiple different ones.
This way, the inside of the Create() method can be different for different classes, without affecting the "outside" code, which calls this method. All the outside code has to know is that the method Create() has 1 parameter ($personObject), because that's how the outside code will use/call the method. The outside code doesn't care what's happening inside the method; it only has to know how to use/call it.
You can do this without an interface as well, but if you use an interface, it's "safer" (because it prevents you to make mistakes). The interface assures you that the method Create() will have the same signature (same types and a same number of parameters) in all classes that implement the interface. This way you can be sure that ANY class which implements the IPersonService interface, will have the method Create() (in this example) and will need only 1 parameter ($personObject) to get called/used.
A class that implements an interface must implement all methods, which the interface does/has.
I hope that I didn't repeat myself too much.
The difference between using an interface and an abstract class has more to do with code organization for me, than enforcement by the language itself. I use them a lot when preparing code for other developers to work with so that they stay within the intended design patterns. Interfaces are a kind of "design by contract" whereby your code is agreeing to respond to a prescribed set of API calls that may be coming from code you do not have aceess to.
While inheritance from abstract class is a "is a" relation, that isn't always what you want, and implementing an interface is more of a "acts like a" relation. This difference can be quite significant in certain contexts.
For example, let us say you have an abstract class Account from which many other classes extend (types of accounts and so forth). It has a particular set of methods that are only applicable to that type group. However, some of these account subclasses implement Versionable, or Listable, or Editable so that they can be thrown into controllers that expect to use those APIs. The controller does not care what type of object it is
By contrast, I can also create an object that does not extend from Account, say a User abstract class, and still implement Listable and Editable, but not Versionable, which doesn't make sense here.
In this way, I am saying that FooUser subclass is NOT an account, but DOES act like an Editable object. Likewise BarAccount extends from Account, but is not a User subclass, but implements Editable, Listable and also Versionable.
Adding all of these APIs for Editable, Listable and Versionable into the abstract classes itself would not only be cluttered and ugly, but would either duplicate the common interfaces in Account and User, or force my User object to implement Versionable, probably just to throw an exception.
Interfaces are essentially a blueprint for what you can create. They define what methods a class must have, but you can create extra methods outside of those limitations.
I'm not sure what you mean by not being able to add code to methods - because you can. Are you applying the interface to an abstract class or the class that extends it?
A method in the interface applied to the abstract class will need to be implemented in that abstract class. However apply that interface to the extending class and the method only needs implementing in the extending class. I could be wrong here - I don't use interfaces as often as I could/should.
I've always thought of interfaces as a pattern for external developers or an extra ruleset to ensure things are correct.
You will use interfaces in PHP:
To hide implementation - establish an access protocol to a class of objects an change the underlying implementation without refactoring in all the places you've used that objects
To check type - as in making sure that a parameter has a specific type $object instanceof MyInterface
To enforce parameter checking at runtime
To implement multiple behaviours into a single class (build complex types)
class Car implements EngineInterface, BodyInterface, SteeringInterface {
so that a Car object ca now start(), stop() (EngineInterface) or goRight(),goLeft() (Steering interface)
and other things I cannot think of right now
Number 4 it's probably the most obvious use case that you cannot address with abstract classes.
From Thinking in Java:
An interface says, “This is what all classes that implement this particular interface will look like.” Thus, any code that uses a particular interface knows what methods can be called for that interface, and that’s all. So the interface is used to establish a “protocol” between classes.
Interfaces exist not as a base on which classes can extend but as a map of required functions.
The following is an example of using an interface where an abstract class does not fit:
Lets say I have a calendar application that allows users to import calendar data from external sources. I would write classes to handle importing each type of data source (ical, rss, atom, json) Each of those classes would implement a common interface that would ensure they all have the common public methods that my application needs to get the data.
<?php
interface ImportableFeed
{
public function getEvents();
}
Then when a user adds a new feed I can identify the type of feed it is and use the class developed for that type to import the data. Each class written to import data for a specific feed would have completely different code, there may otherwise be very few similarities between the classes outside of the fact that they are required to implement the interface that allows my application to consume them. If I were to use an abstract class, I could very easily ignore the fact that I have not overridden the getEvents() method which would then break my application in this instance whereas using an interface would not let my app run if ANY of the methods defined in the interface do not exist in the class that implemented it. My app doesn't have to care what class it uses to get data from a feed, only that the methods it needs to get that data are present.
To take this a step further, the interface proves to be extremely useful when I come back to my calendar app with the intent of adding another feed type. Using the ImportableFeed interface means I can continue adding more classes that import different feed types by simply adding new classes that implement this interface. This allows me to add tons of functionality without having to add unnecessarily bulk to my core application since my core application only relies on there being the public methods available that the interface requires so as long as my new feed import classes implement the ImportableFeed interface then I know I can just drop it in place and keep moving.
This is just a very simple start. I can then create another interface that all my calendar classes can be required to implement that offers more functionality specific to the feed type the class handles. Another good example would be a method to verify the feed type, etc.
This goes beyond the question but since I used the example above:
Interfaces come with their own set of issues if used in this manner. I find myself needing to ensure the output that is returned from the methods implemented to match the interface and to achieve this I use an IDE that reads PHPDoc blocks and add the return type as a type hint in a PHPDoc block of the interface which will then translate to the concrete class that implements it. My classes that consume the data output from the classes that implement this interface will then at the very least know it's expecting an array returned in this example:
<?php
interface ImportableFeed
{
/**
* #return array
*/
public function getEvents();
}
There isn't much room in which to compare abstract classes and interfaces. Interfaces are simply maps that when implemented require the class to have a set of public interfaces.
Interfaces aren't just for making sure developers implement certain methods. The idea is that because these classes are guaranteed to have certain methods, you can use these methods even if you don't know the class's actual type. Example:
interface Readable {
String read();
}
List<Readable> readables; // dunno what these actually are, but we know they have read();
for(Readable reader : readables)
System.out.println(reader.read());
In many cases, it doesn't make sense to provide a base class, abstract or not, because the implementations vary wildly and don't share anything in common besides a few methods.
Dynamically typed languages have the notion of "duck-typing" where you don't need interfaces; you are free to assume that the object has the method that you're calling on it. This works around the problem in statically typed languages where your object has some method (in my example, read()), but doesn't implement the interface.
In my opinion, interfaces should be preferred over non-functional abstract classes. I wouldn't be surprised if there would be even a performance hit there, as there is only one object instantiated, instead of parsing two, combining them (although, I can't be sure, I'm not familiar with the inner workings of OOP PHP).
It is true that interfaces are less useful/meaningful than compared to, say, Java. On the other hand, PHP6 will introduce even more type hinting, including type hinting for return values. This should add some value to PHP interfaces.
tl;dr: interfaces defines a list of methods that need to be followed (think API), while an abstract class gives some basic/common functionality, which the subclasses refine to specific needs.
I can't remember if PHP is different in this respect, but in Java, you can implement multiple Interfaces, but you can't inherit multiple abstract classes. I'd assume PHP works the same way.
In PHP you can apply multiple interfaces by seperating them with a comma (I think, I don't find that a clean soloution).
As for multiple abstract classes you could have multiple abstracts extending each other (again, I'm not totally sure about that but I think I've seen that somewhere before). The only thing you can't extend is a final class.
Interfaces will not give your code any performance boosts or anything like that, but they can go a long way toward making it maintainable. It is true that an abstract class (or even a non-abstract class) can be used to establish an interface to your code, but proper interfaces (the ones you define with the keyword and that only contain method signatures) are just plain easier to sort through and read.
That being said, I tend to use discretion when deciding whether or not to use an interface over a class. Sometimes I want default method implementations, or variables that will be common to all subclasses.
Of course, the point about multiple-interface implementation is a sound one, too. If you have a class that implements multiple interfaces, you can use an object of that class as different types in the same application.
The fact that your question is about PHP, though, makes things a bit more interesting. Typing to interfaces is still not incredibly necessary in PHP, where you can pretty much feed anything to any method, regardless of its type. You can statically type method parameters, but some of that is broken (String, I believe, causes some hiccups). Couple this with the fact that you can't type most other references, and there isn't much value in trying to force static typing in PHP (at this point). And because of that, the value of interfaces in PHP, at this point is far less than it is in more strongly-typed languages. They have the benefit of readability, but little else. Multiple-implementation isn't even beneficial, because you still have to declare the methods and give them bodies within the implementor.
Interfaces are like your genes.
Abstract classes are like your actual parents.
Their purposes are hereditary, but in the case of abstract classes vs interfaces, what is inherited is more specific.
I don't know about other languages, what is the concept of interface there. But for PHP, I will try my best to explain it. Just be patient, and Please comment if this helped.
An interface works as a "contracts", specifying what a set of subclasses does, but not how they do it.
The Rule
An Interface can't be instantiate.
You can't implement any method in an interface,i.e. it only contains .signature of the method but not details(body).
Interfaces can contain methods and/or constants, but no attributes. Interface constants have the same restrictions as class constants. Interface methods are implicitly abstract.
Interfaces must not declare constructors or destructors, since these are implementation details on the class
level.
All the methods in an interface must have public visibility.
Now let's take an example.
Suppose we have two toys: one is a Dog, and other one is a Cat.
As we know a dog barks, and cat mews.These two have same speak method, but with different functionality or implementation.
Suppose we are giving the user a remote control that has a speak button.
When the user presses speak button, the toy have to speak it doesn't matter if it's Dog or a Cat.
This a good case to use an interface, not an abstract class because the implementations are different.
Why? Remember
If you need to support the child classes by adding some non-abstract method, you should use abstract classes. Otherwise, interfaces would be your choice.
Below are the points for PHP Interface
It is used to define required no of methods in class [if you want to load html then id and name is required so in this case interface include setID and setName].
Interface strictly force class to include all the methods define in it.
You can only define method in interface with public accessibility.
You can also extend interface like class. You can extend interface in php using extends keyword.
Extend multiple interface.
You can not implement 2 interfaces if both share function with same name. It will throw error.
Example code :
interface test{
public function A($i);
public function B($j = 20);
}
class xyz implements test{
public function A($a){
echo "CLASS A Value is ".$a;
}
public function B($b){
echo "CLASS B Value is ".$b;
}
}
$x = new xyz();
echo $x->A(11);
echo "<br/>";
echo $x->B(10);
We saw that abstract classes and interfaces are similar in that they provide abstract methods that must be implemented in the child classes. However, they still have the following differences:
1.Interfaces can include abstract methods and constants, but cannot contain concrete methods and variables.
2.All the methods in the interface must be in the public visibility
scope.
3.A class can implement more than one interface, while it can inherit
from only one abstract class.
interface abstract class
the code - abstract methods - abstract methods
- constants - constants
- concrete methods
- concrete variables
access modifiers
- public - public
- protected
- private
etc.
number of parents The same class can implement
more than 1 interface The child class can
inherit only from 1 abstract class
Hope this will helps to anyone to understand!
Related
In Doctrine, assuming I want to implement different types of vehicles. Maybe a car, a plane, a bicycle and so on ... all these vehicles have many different properties but also very common things like they are all made of a material.
So if i want to get this material ... should i implement a abstract class Vehicle with a property material and implement getter/setter or should i define a interface IVehicle and define the getter/setter in there to be sure there is really a method for getting and setting the material? Or should i even use both in combination?
It feels "professional" using the interface ... but it feels wrong to define getter/setters in interfaces, so my personal feeling is:
Don't use an interface, just use the abstract class.
But is the abstract class approach protected against misuse? For example on another place i definitely expect a Material type returning from the getMaterial function ... is the abstract class approach also save for not returning complete unexpected things (like the interface does)?
So if i extend this vehicle for another concrete class, a developer should not be able to return unexpected things, but should also be able to change the logic in the particular method if needed.
My 2 cents:
You can write an abstract class with methods that return null (or some other predetermined value) that would require you to implement them in every derived class.
This approach would still require you to write some boilerplate code to check against your conditions in every class.
I would personally go with an interface here as the nature of your classes seem to be quite diverse and can only be partially generalized to a single abstract class. However, I don't see anything wrong with going the abstract class way either. In this case, the devil is in the details.
I've been reading up about PHP's traits. Specifically I came across this article. They probide an example involving objects that need to implement a shareable interface. The following argument is presented:
Does it make sense to duplicate the share() method in every class that implements the Shareable interface?
No.
Does it make sense to have an AbstractShare class that objects who implement the Shareable interface extend?
No.
Does it make sense to have the share() method implemented as part of an AbstractEntity class, but then blocked out for the Message object?
No.
Does it make sense to implement a ShareableTrait that fulfils the interface contract and can therefore be easily added to only objects that require it?
Yes!
I can understand the first and third points. But the second one confuses me. What exactly is wrong with having an abstract class called AbstractShareable or something like that which contains the functionality to share something, and then extending from it?
An interface is specifically designed to create reliable, well, interfaces, independent of the implementing class. Meaning:
function (Shareable $sharable) {
$shareable->share();
}
You can be assured that this code will always work (any object being passed in having a share() method), due to your interface declaration.
You can achieve the same thing using a class hierarchy; i.e. if you require a certain class, you can be sure that all of its children will also have the same methods the parent has. But: this imposes a strict class hierarchy on your classes. All classes have to extend one specific base class. And they can only extend that one specific class. You couldn't use a class hierarchy for both an AbstractSharable and an AbstractLoggable, say. That's why the class hierarchy solution is too inflexible. It would only allow you to implement one "trait". Or you'd have to mash all your various "traits" together into the same base class. Then you have a giant monolithic base class.
Separating characteristics into small individual interfaces keeps your code simple and flexible. Traits provide a flexible implementation analogue to an interface's specification.
So, I am starting to gasp the concept of abstract and interface in PHP.
But when is it really ever useful?
Sure I can with an interface make up the rules for my classes, so they all follow a specific pattern. But when is it really useful?
And why should I make an abstract class instead of just making a class that works by it own but is useful for other classes.
Abstract I perhaps can put my head around and see a good use, for example by making a general class. Like making a abstract Database class, then extending it onto a Mysql- and a MsAccess database class. Giving both similar functions to work with, allowing seamless experience in both cases.
But really, could anyone give me a better example of when abstract and interface are really useful?
And please note, I do know how it works, or how to write the code, just not how or when to use it.
Thanks!
Abstract means "here is a pattern for your class, and some code that can start you off". The designer of the abstract class can mark some methods as needing to be provided by the extending class (abstract), or as final, which means the class can't override them.
Interface means "here is a pattern for your class, but you have to write all the code yourself". Any methods and properties declared in the interface must be provided by the class that implements the interface.
So essentially a rule of thumb will be:
If you have code that can or must be used by the descendant classes, you need an abstract class. If you only have method and property declarations, you can use an interface.
Don't forget, using abstract classes limits you to some extent, because a descendant class can only extend one class, whereas it can implement any number of interfaces.
An interface is not a class, while an abstract class is already a class.
As every class has an interface (by definition), the interface allows you to specify an interface next to any class, be it abstract or not.
Programming against interfaces then allows you to replace one class with another one while keeping the same interface. So it makes your code less coupled. It's not programmed against concrete classes any longer but "only" against more lightweight interfaces. An interface then is useful if you don't want to program against concrete class names but against types. You can replace an object then with any other object that implements the same interface.
An abstract class on the other hand - even called abstract - is pretty concrete. However, it's not final, so it forms a pattern of a class, like a specification how a class that extends from it should be written for a certain functionality. As it's abstract, it can't come to live without extending from it. Abstract classes are used to create base classes with code that will be used more than once to reduce code duplication and not being able to instantiate directly.
An interface works like a contract. If a class implements an interface, other code that uses this class now knows it supports certain features.
The best example of an interface in PHP is the Iterator interface.
The benefit of interfaces is that classes can implement multiple. 'Extending' does not allow this. This means that a subclass can implement an interface, but it's parent doesn't have to.
Read up on design patterns. A lot of this you'll find covered, and you'll never have doubt again in which cases it makes sense. 'Head first design patterns' I thought to be a good book, very nicely written. Although they use Java in their examples, most stuff is very much applicable in PHP.
I have one more real-life scenario.
Our application always throws exceptions everywhere whenever an error occurs. Every type of exception gets its custom class. An example of this is a RecordNotFound exception.
If exceptions are not caught, there's a top-level exception block, which looks a bit like this:
try {
// Do everything in the app!
} catch (Exception $e) {
// draw a good error page
}
In some cases exceptions need to be mapped to certain HTTP status codes, such as 404 (not found). Therefore we have this interface:
interface HTTPException {
function getHTTPCode();
}
any exception, no matter how deep in the inheritance tree can now implement this interface and emit a specific HTTP status code.
I even created interfaces, without any methods. I'll leave it to you to try to think of a reason why that may makes sense.
Interface is nothing but the skeleton structure of a class and it is not class. we can just implement that class and add some extra feature to make more clear. The implements keyword can be used for interface .In general way implement is used in interface to implementing the features.
abstract is a class which hides some of features and only just shows the necessary features. Extend keyword can be used for abstract class. In general ways extends can be used to extends the features of abstract class.
I have a confusion in why we use abstract classes or interfaces to implement or extend. interfaces doesn't contain any code so does the abstract methods. then why we use them. why don't we directly create methods and define them in our class rather we use interfaces or abstract classes. they don't contain any sort of code, we need to define them after extending them in our class. why we don't define these methods in our own class rather extend interfaces and then define them. I found such type of question asked several times in stackoverflow but couldn't understand the answer. can anyone please explain it in some simple way
The power of abstraction and interfaces comes from the fact that you can separate responsibilities and write modular code: One part of your (or someone else's) code may only care that you have an Animal and provide facilities to deal with Animals, without needing to know how they move or feed. A different part of your code may only care about defining lots of concrete animals, like Dogs, Birds, etc., with all the details of how they actually implement all their features.
By making the concrete classes (Dog, Bird, ...) extend a common, abstract interface (Animal), you can use a any now and future concrete class in a library written for the abstract interface -- you don't need to ask the library author to change the library to accommodate new Animals, and the library author doesn't need to know how features are concretely implemented.
For example, if you had two single algorithm, FeedBreakfast and FeedDinner, that would require a member function Animal::gobble(), then without inheritance you would need to implement each algorithm for each animal - i.e. you'd end up with M * N amount of code! By using a common, abstract interface you reduce this to M + N -- M algorithms and N concrete classes, and neither side needs to know of the other -- they just both need to know the interface.
Statically typed languages need to use this method to enable polymorphism. That is, you can write your code in terms of your abstract base class. Then you can "plug" in any subclass as an extension. This is called Liskov Substitution principle, or Open/Closed principle. Technically, this is called dynamic binding. That is, the method to call is selected during runtime depending on the subclass.
With dynamically typed languages the situation is completely different. I don't know if PHP is dynamically typed (I suspect it is), but in Ruby or Javascript, for example, you can program in terms of any object that conforms to a specific interface. That is, if your code expects an object that has a method called Print you can substitute with any other object that also has a Print method, without deriving from a common base class. The method will be looked up during runtime, that is why these languages are called "dynamic".
Hope this helps!
You use abstract classes or interfaces when you want to establish a protocol.
It sounds simple, but it's a very powerful concept. If you are forced to adhere to rules, then you cannot break them. If you cannot break the rules, you adhere to the protocol. Therefore, all the classes that implement your interface should inherently be compatible with each other. Naturally, there are exceptions among human kind who are able to break these rules by creating code that even interpreters cry when they have to parse it but that's a bit of an offtopic :)
For an interface, imagine you have a Class called "Message". This implements the Interface called SendMessage, which has a method definition of Send.
If you then create two subclasses of "Message". One could be "Email" and one could be "InstantMessage".
Now these both have the method Send(), which is defined in the SendMessage interface, and are blank. This now allows you to define differently what the Send() method does. However, because we know the classes Email, and InstantMessage use the interface SendMessage, we know that they both have the method Send();
So you could call Email.Send(), and InstantMessage.Send(), but do two different things. An interface defines methods available to several objects, but with the same method name.
Abstract classes/interfaces are mostly design time considerations. By defining methods as abstract and therefore the classes as abstract too.. we are ensuring that these methods will definitely be implemented by deriving classes. If they do not implement them they also become abstract.
Interfaces provides the luxury of distributing the must implement methods into different categories, so the required number of interfaces can be implemented.
the abstract classes guarantee that can't be instantiate, this is because are a generalization. for example,
in a game, exist a class player, but also exist classes defender and forward. the class player is the parent class of both classes. not is practice create a object player, because a team need a especific player.
The interfaces are related with polymorphism. every class, use methods according to its behavior.
i hope this help you
The idea behind an abstract class is that you can define some common functionality of a set of similar classes, but leave other details up to the implementing (extending) classes. In a way they are similar to interfaces, except that you can actually implement some of the functions in the abstract class.
But what's the point, I hear you ask? Well, you only have to write the common code once, although you can do this in a concrete (non-abstract) base class too. But also you may not want other programmers to instantiate the base class, so this is where the real power of abstract classes come in.
Let me show an example to help illustrate my point. Imagine you are writing a program to classify all of the animals in a zoo. Animals can be classified into certain types, bird, reptile, mammal, insect, arachnid, fish, etc, and then down to their species such as dog, cat, parrot or kangaroo. The base class, Animal, can provide some of the common functionality to all of these. It might have a function called eat() which all animals do in a similar way and so the function is written out to describe the process of an animal eating. It might contain another function, walk(), but this one is abstract, since different animals will implement this in a different way. All subclasses of the Animal class will need to implement this method.
The major bonus of this is that somewhere in your code you can call a function that takes an Animal as a parameter. You know that you can call the eat() and walk() functions on this parameter because all Animals can eat and walk. This is called polymorphism and is an important trait of Object Oriented Programming.
I hope this has helped you. Please feel free to discuss or ask further questions if you still can't see the value of abstract classes.
I have always had a hard time understanding the real value of Interfaces when coding with Objects in PHP (could be other languages I imagine)
From what I understand you use an Interface to enforce or guarantee that when a Class is using an Interface that that class will have the methods defined in the Interface inside of that class.
So from my litte knowledge of using them, wouldn't that mean you would only find an Interface beneficial when defining more then 1 class that needs those Methods?
To be more clear, if I have a class that does one thing and no other classes need to do that kind of thing, then it would be pointless to use an Interface on that class?
So you wouldn't use an Interface on EVERY class you right?
PS) If you vote this question as exact duplicate then you didn't read the question and only the title as I have read most of the similar questions already
From what I understand you use an Interface to enforce or guarantee
that when a Class is using an Interface that that class will have the
methods defined in the Interface inside of that class.
This is actually only half of the deal (the technical part). There's also the all-important architectural half, which appears when you consume the interface and it goes like this:
function feed(IAnimal $interface) {
// ...
}
(alternatively, a "factory" function that is documented to return an instance that implements IAnimal would also serve as an example).
The idea here is that the consumer of the interface says: "I want an animal to feed. I don't care if it flies, walks, or crawls. I don't care if it's big or small. I only care that it shares some features with all other animals" -- features that would comprise the definition of the interface.
In other words, interfaces serve to abstract the contract (interface) from the concrete implementation (classes). This gives implementers of concrete classes a free hand to modify, rename, remove and add implementations without breaking the code for users of the interface, something that is not possible if you are referencing concrete classes directly in your API.
As for the interface that is implemented by one class only: that's not enough information to decide. If there can plausibly be more implementations of the interface in the future, then it certainly does make sense (for example: an IHashFunction interface would make sense even if Sha1HashFunction were currently the only available implementation). Otherwise it doesn't offer anything.