Difference class and interface [duplicate]

4

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

    
asked by anonymous 22.06.2016 / 03:35

1 answer

5

Classes are complete data structures. They possess, or at least may possess, state and behavior. So they are composed of several variables and methods including the implementation of the methods. Normal classes can be instantiated (create objects according to their structure). It can be inherited from classes (usually).

Interfaces are just contracts. They only have the statement of method signatures that must exist in a class to conform to an interface. In general 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 slightly according to the language, so be careful not to learn the concept of a language and find that it applies the same in all of them.

The abstract classes , roughly speaking, are the middle ground between classes and interface, since they can have methods without implementation. They can only be inherited , they can not 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 a little strange in dynamically typed languages, after all they do not value much by contract.

You have a question showing when to use interfaces and several links on the subject. There is a chain that preaches that you should prefer the interface whenever possible . But can not overdo it .

Practical example of difference in C # .

    
22.06.2016 / 03:58