What is the diff between interface and abstract class? When will you go for abstract class, and when will you go for interface? Please provide any examples if possible
When you know what your class can do but do not know how; then make it an Interface. i.e. You just know the behaviour; how part is left for the classes implementing this Interface.
Comming to Abstract class: You know what your class does (i.e. behaviour) but only partially or in a generic way; then you go for Abstract declaration. More concrete implementation will be done by the extending classes.
Tip : Avoid abstract classes and use interfaces
You can't wake a person who is <b><i>pretending</i></b> to be asleep.<br />Like what <b>"it"</b> does not like - <i> Gurdjieff </i>
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
Tip : Avoid abstract classes and use interfaces
Disagree. Abstract classes can be very useful. This has been discussed before, and check the links given earlier first.
If you have behaviour, but don't know how it is to be implemented, you are looking at an interface. Particularly if you are already inheriting from another class; you can't inherit from two classes in Java. Interfaces have a selection of methods, but all abstract, so they will be implemented differently every time they are used.
If you have entities which can be put into a very general title, you are better off using an abstract class. If you have a method which will be the same in (at least a large majority of) the subclasses, write the method. If you have a method which will eb different in most cases, use an abstract method.