Interface:
Interfaces will be declared only with method declarations, there will not be method definition. In general all methods are implicitly abstract methods in Interface. Suppose if a Interface declared without any method declaration or variable, then its a Marker Interface. As same as Abstract class few other questions which may be on Interface are,
Interface can have variable or not?
Answer: Yes we can have but it should be Final variable.
Interface can extend other class ?
Answer: No, Interface can extends only other interfaces.
How many Interfaces can be extended in a single Interface?
Answer: Interface can extends multiple Interfaces like below
Difference between Abstract class and Interface?
- Abstract class can have Abstract method and as well as concrete methods. But Interface always should will have Abstract methods.
- Overriding all the Abstract method is not mandatory while we extends Abstract class. But if its a Final class then we need to Override all abstract methods. On other hand when we implements Interface we need to Override all abstract methods in our class. Only in case of Abstract class we don't need to provide implementation (Override) for all methods in Interface.
- Abstract class methods can have any access modifiers. But Interface methods should be always public.
- As we seen above Abstract class and extends only one class, where as Interface can extends multiple Interfaces.
- Abstract class can have Final and non-Final variables. Where as Interface can contain only Final variables.
- Abstract class can have Constructors, but Interface cannot have Constructor.
- As by performance Abstract class will be faster than Interface since it consumes little more time on routing to Override methods.
- When we add any new methods in Abstract class then the base classes won't get affected. But in case of Interface if we add any method then all implemented classes will get affected and need to implemented those new methods also.
When to use Abstract class and Interface in Java?
Whenever we talk about When to use Abstract class and Interface in Java will lead to a multiple questions and answers. So in that case programmer need to decide to choice his best in his design stage. Lets see few choices of using Abstract class or Interface according to our needs,
- Abstract class is more suited for code reuse like inheritance, where as Interfaces are better suited for Type declaration.
- Using Interface will be suitable if we feel API will be stable for quite long time.
- Abstract classes are better if we add any methods in our future, since it won't break the code.
- Abstract class will be better when we have common method definition and also non public methods and variables.
- Interface will be better when we need similar to multiple inheritance.
- Best suitable for Template pattern will be Abstract class declaration.
- Prefer Interface for providing more design flexibility.