Class and interface difference

Asked

Viewed 3,121 times

6

What is the difference between class and interface and when I should use one or the other?

1 answer

7


Classes are complete data structures. They have, or at least can have state and behavior. Then they are composed of several variables and methods including the implementation of the methods. Normal classes can be instantiated (creating objects according to their structure). One can inherit from classes (usually).

Interfaces are only contracts. They only have the statement of method signatures which must exist in a class to conform to an interface. In general, but not always, they have no implementations (code) of the methods and no data. Interfaces can only be used in conjunction with classes or other interfaces (inheritance).

Both are data types and their details may vary somewhat according to the language, so be careful not to learn the concept of a language and find that it applies equally in all of them.

As abstract classes, roughly speaking, they are the middle ground between classes and interface, since they can have methods without implementation. They can only be inherited, cannot have concrete instances directly.

There are languages that allow some interface implementation, but in a limited way. Some languages do not have specific syntax for interfaces, but the concept can be applied.

Interfaces sound quite strange in dynamically typed languages, after all they do not care much for contracts. Not that other structures are much better, these "modern" dynamic typing languages are pretty weird, they don’t seem to know where they want to go, they lack insight into what matters to them, and some people consider that they are conceptually wrong by definition.

Has a question showing when to use interfaces and several links on the subject. There is a chain that preaches that one should prefer the interface whenever possible. But can’t exaggerate.

Practical example of the difference in C#. And about PHP (for me the biggest example of wrong use of interface, unless they give up on having dynamic typing, which is almost walking, but impossible at the current stage, without breaking everything that exists, ie, they wanted something else for this language, but they started out the way they didn’t want to.

  • Enlightened, Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.