In this tutorial we will learn “when we use interface and abstract class in java” and what is the significance of interface and abstract class
The question “when we use interface and abstract class in java ? ” is very common in lot of java interviews , let us have a look.
To answer the above question, we should have good understanding of OOPS concepts like Inheritance , Polymorphism , Abstraction and Encapsulation, and also it is important to know about coupling and cohesion why because these are very useful design consideration during software development. There are lot of differences between Abstract class and Interface.
When we use interface .
1. In general Java does not have multiple inheritance, some times we will face some design issues regarding multiple inheritance functionality during development in those cases it is very Good option to use Interface.
2. If we want to provide our services to public access then go for Interfaces.
3. Interfaces are really fit when we want to make functionality as standardized.
4. In some design scenarios like if we want to implement some patterns interfaces are very good option , for example “Dependency Injection design pattern”.
5. Prefer Interfaces when ever you want to implement decoupling designs why because interface doesn’t contain any implementation detail by default.
When we use Abstract class .
1. If you want to provides a common base class implementation to derived classes then use Abstract class, for example if we have 100 derived classes want to use same functionality then we implement that functionality in abstract class and all the 100 derived classes can extend that abstract class , so that all the derived classes will use.
2. If we are keep on doing functional changes (adding new methods) to the prefer Abstract class because the existing functionality will not break, but if you use interface in such kind of case the existing functionality will break.
3. If we want to declare non-public members prefer Abstract class In an interface, all methods must be public.
4. Prefer Interfaces when ever you want to implement coupling designs why because Abstract class contain default implementation .
Happy learning Java Tutorial.. 🙂
Abstract Classes are classes in Java, that declare one or more abstract methods. For design purpose, a class can be declared abstract even if it does not contain any abstract methods . Many thanks for sharing this.