How interface in java works and how to achieve abstraction using the interface.
In java, we can achieve abstraction in two ways, using abstract class and Interface. We have seen Abstraction in Java in this blog we will see how interface in java works and how to achieve abstraction using the interface.
What is Interface in java?
This is a class in java that has static constants and abstract methods. From Java-8 onwards, we can also have default and static methods in an interface and from Java-9 onwards we can have private methods. Java interface represents has-a relationship.
An interface can not be initiated.
Why interface is used in java?
- To achieve abstraction in java.
- To achieve multiple inheritances.
Example for interface in java:
Note that:
1. All the variables in java are by default public static final. This means we need to assign the value at the time of initialization else we will get a compile-time error.
2. For abstract methods, we can remove an abstract keyword, the interface by default make it a public abstract.
3. All the abstract methods in an interface need to implement in child class.
4. If we have InterfaceA and InterfaceB we can implement both by child class to achieve Multiple Inheritance as shown below. Two interfaces are separated by a comma. Even if Multiple Inheritance is not supported in the java class(i.e we can not extend multiple classes) we can achieve it by implementing an interface.
5. If InterfaceA and B both have the same methods with different return types, and Child1 is implementing both of them we will get compile time issue. Hence when Child is implementing 2 different interfaces, they must have 2 different methods or the same method with the same return type.
6. Static methods in an interface can be called by directly using the interface name as shown in the first example.
7. We can not create an object of an interface.
8. We can not have a constructor within an interface, unlike abstract class.
9. We can also have a child interface extending the parent interface.