Possible Duplicate:
When to use abstract classes instead of interfaces and extension methods in C#?
When I read and looked at codes using Abstract classes, I was able to justify it because it allows you to add common methods for any subclasses extending the abstract class. So for example, if objects behavior is similar, I would use Abstract classes to implement bodyless abstract methods that is required for each object, and simply use non abstract methods already implemented in the abstract class. I can think of a scenario dealing with multiple media file types (avi,mpg,mp4) and you would have common methods for all files, as well as media specific abstract methods that needs to be implemented.
However, I am a bit confused as to why you would knowingly create an interface which cannot contain any non-abstract methods. Reading this page, it states that it hides information (you mean the abstract methods?).
Hiding details and providing common interfaces is called encapsulation, which is an analogy from making an object look like it's covered by a capsule (the interface in this case). This allows two objects differing in internal representation but having the common interface interchangeably usable (called interchangeability). Interfaces also allow to facilitate the use of data structure and guard the state of the object from invalid inputs and modification of the structure.
So does this mean that any objects which share the common behaviors implemented uniquely can be treated like they are the same category? So for the media file example, does this mean any specific media file type implementing the interface MediaFile
are to be passed as arguments for a method dealing with such type of objects?
public class ServiceClass {
public ServiceClass(){
//no-args constructor
}
public boolean runService(ICollaborator collaborator){
if("success".equals(collaborator.executeJob())){
return true;
}
else
{
return false;
}
}
}
But can't you do above with an abstract class? Also, isn't the ability of having a non-abstract method better than having none at all for the future when you suddenly need to have an existing method that will apply to all classes extending the abstract class?
Or is the difference of using Interface, the ability to protect the implementation of data completely? Once again, I don't see what cases you would use it. Other than that I implement ActionListener
quiet often to have the actionPerformed
method.