Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.
abstractkeyword is used to create an abstract class and it can be used with methods also whereasinterfacekeyword is used to create interface and it can’t be used with methods.- Subclasses use
extendskeyword to extend an abstract class and they need to provide implementation of all the declared methods in the abstract class unless the subclass is also an abstract class whereas subclasses useimplementskeyword to implement interfaces and should provide implementation for all the methods declared in the interface. - Abstract classes can have methods with implementation whereas interface provides absolute abstraction and can’t have any method implementations.
- Abstract classes can have constructors but interfaces can’t have constructors.
- Abstract class have all the features of a normal java class except that we can’t instantiate it. We can use
abstractkeyword to make a class abstract but interfaces are a completely different type and can have only public static final constants and method declarations. - Abstract classes methods can have access modifiers as public, private, protected, static but interface methods are implicitly public and abstract, we can’t use any other access modifiers with interface methods.
- A subclass can extend only one abstract class but it can implement multiple interfaces.
- Abstract classes can extend other class and implement interfaces but interface can only extend other interfaces.
- We can run an abstract class if it has
main()method but we can’t run an interface because they can’t have main method implementation. - Interfaces are used to define contract for the subclasses whereas abstract class also define contract but it can provide other methods implementations for subclasses to use.
No comments:
Post a Comment