What to choose between abstract class and interface if…
Omar Ismail
Senior Software Engineer @ Digitinary | Java 8 Certified? | Spring & Spring Boot?????? | AWS? | Microservices ?? | RESTFul Apis & Integrations ?? FinTech ?? | Open Banking ?? | Digital Payments and Transformation??
You know that interface contains only abstract methods. But, consider the restriction that abstract class has only abstract methods only, then what would be your choice and why? Here is an example.
Answer:
Best choice is an interface for two reasons given below.
1)Missing a chance of multiple inheritance
Since multiple inheritance is not supported in java, you cannot inherit your class from two abstract classes or one abstract and other concrete class. But, if you use interface the still you have a chance to extend a class.
For given interface and classes below, you cannot extend two classes but interface
class C extends A implements X{}//OK, on class and multiple interfaces can be extended and implemented.
class C extends A ,B{} // wrong, two classes cannot be extended.
?
2) User / Programmer intent:
Depending what you choose between abstract class and interface to provide contracts, your contracts can be easily violated by users or programmer’s intent.
Let’s consider a scenario.
Let’s say you are a client and pass the?contracts in an interface?to implement them to development team for multiple types of documents e.g. pdf, rtf and word etc. Constricts example is below, that team need to implement header, body and footer.
?All development team understand easily that they must just implement and do nothing extra. this is what you want as a result.
?
领英推荐
Now you pass these?contracts in an abstract class as below.
?
abstract class Doc{
abstract void header();
abstract void body();
abstract void footer();
}
Programmers from team get intention that they are free to implement another interface besides given one in abstract class.
Also, they can write their own methods (private or public) into the abstract class, if they think it is required during implementation of sub classes i.e. pdf, rtf and word etc.?This is not the client want.
Reasons to use Abstract Classes in Java
Reasons to use Interfaces in Java
When should you use Java Interfaces?
You should use interfaces when:
When should you use Java Abstract Classes?
You should use abstract classes when:
Java | Flutter Developer
3 年Abstract class is faster than interface?? Is it depend on code implementation!!. https://stackoverflow.com/questions/51112973/are-abstract-classes-faster-than-interfaces-in-java https://stackoverflow.com/questions/10040069/abstract-class-vs-interface-in-java?answertab=votes#tab-top
Senior Full-Stack Java Developer | J2EE | SpringBoot | React Js | AWS
3 年Interface cannot implement several Interfaces but extend or you mean to say Class
Android Engineer | Kotlin Enthusiast
3 年How Abstract class is faster than interface? What do you mean by fast? Also in modern java, interface could have fields.