I'm new to OOP. Can I say Interface is a set of general behavior that may be have and act uniquely by a set of objects that have in common? And Abstract class has similarity with Interface but it have default method that also can be have and perform by a set of objects? Thanks
3 Answers
No. Commonly you would say:
An Interface is a contract
An Abstract class is a class which you can't have an instance of
No, an interface in a strict sense does not have any behaviour at all.
It defines formal rules of interaction.
To be more concrete, it defines the types of inputs (arguments) and outputs (returns) of methods but makes no assertion about how the output values depend on the inputs and what side effects a method call might have.
I like to add thet in Java 8, you have the option to add behaviour in interfaces by defining default methods, that's why I wrote "in a strioct sense" in the beginning.
"General behavior" isn't what an interface is about.
Understand that interface can mean two different things in OOP.
The intrinsic interface of an object is really just a set of messages you can send it by calling it's methods. There is no behavior defined here.
There is also the explicit interface type that some languages have. This competes with abstract classes but has a slightly different set of rules depending on your language.
With abstract types you can define behavior that can be overridden that you can think of as "general behavior". You can do this same trick in some versions of some languages with a type that they unfortunately decided to call "interface".
These explicit interfaces were only recently given this ability. They added it because they wanted to not break legacy code when they expanded published interfaces. This let them provide what I prefer to call "default behavior". It's doubtful they'd have named this type "interface" if they knew that it would eventually allow this.
So no, "general" behavior is much more an abstract class thing. Now with composition, it's very much a "default" behavior thing. From the outside though it all looks like the same thing.