Please tell me situation where interface is better than abstract class in Java
9 Answers
I think you have misunderstood the real meaning of interface and abstract class.
Interface is programming structure where you define your functions/services that you want to expose to public or other modules. Kind of a contract where you promise that you are providing some functionalities or services, but hiding the implementation so that implementation can be changed without affecting your contract.
Abstract class is a partially implemented class and it has no real meaning other than serving as a parent for multiple child classes those with real meaning. Abstract class is special parent class that provides default functionalities to multiple child classes. it is created as abstract because of unavailability of suitable concrete parent class.
In a good design, you should always create an interface. But abstract class is optional. If you can not find a concrete parent class, create an abstract class and implement the interface then provide default implementations for those interface functions (if possible) otherwise mark them as abstract functions and leave the implementation to the child classes.
1 Comment
- A class can implement multiple interfaces, but it can only extend one abstract class.
- Interfaces allow the creation of proxies that encapsulate a concrete class. This is used extensively by frameworks in order to intercept method calls to the concrete class (e.g., for starting a transaction before the method is executed or to write to the log).
Comments
Use an interface when you don't need to provide any default implementations.
Here is a nice link comparing the two: Interface vs. Abstract Class
Comments
Abstract Class : Define or Declare a method which is more important. Example: Vehicle must have shape and engine. So we put this behaviour is in Abstract class.
abstract class Vehicle { abstract void shape(); abstract void engine(); } Interface Class : Other than that properties like move, honk, etc. So interfaces that provide additional behaviour to your concrete class.
interface Honk{ void honk(); } interface moveable{ void move(); } class Car extends Vehicle implements Moveable { @Override void shape() { System.out.println("car's shape"); } @Override void Engine() { System.out.println("car's engine"); } @Override void move() { System.out.println("car's can move"); } } But I didn't implements Honk behaviour. If you want you can implements multiple interfaces.