[Solved] Why interface really needed when normal class can do the same work [duplicate]


No doubt your code works even without the interface at this moment, but. Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

For example, if you have multiple animal classes, each implementing Animal, if later on you want to change the structure of the Animal interface, it helps you to easier change the structure of all your animal calsses.

Another example, lets say you work on a group object, and the leader tells you and someone else to make some classes based on a structure given by him (the interface), implementing the interface asures that you got all the method names and structures right. If later on the leader decides that the structure of the classes isn’t good, he will change the interface, forcing you to change your class.

For more information, read What is an interface or Undersanding interfaces and their Usefullness

1

solved Why interface really needed when normal class can do the same work [duplicate]