What is an Interface?
An Interface is like a class in that it can have methods and variables. However, methods declared in an Interface are abstract by default, meaning they only contain the method signature, not the method body.
Facts about Interfaces:
- Interfaces specify what the class must do and not how the class must do it. They are considered as the class blueprint.
- If a class implements an interface, the class must provide all the method bodies for the interface's functions. Otherwise, the class must be declared abstract.
- They are used to achieve total abstraction.
- An Interface can extend one or many Interfaces. A class can extend many Interfaces, but only one class.
- Nested Interfaces is when an Interface is declared inside another interface.
- It is also used to achieve loose coupling.
- Interfaces are used to implement abstraction.
Difference between Abstract Class and Interface:
Differences between an Abstract class and an Interface include:
- An interface can have strictly abstract methods. In comparison, an abstract class can have abstract and non-abstract methods.
- An abstract class doesn't support multiple inheritances, whereas an interface does.
- Interface variables are only static and final. In contrast, an abstract class can have final, non-final, static and non-static variables.
- An abstract class can provide the implementation of an interface. However, an Interface can't provide the implementation of an abstract class.
- The interface keyword declares an interface, and the abstract keyword declares an abstract class.
- An interface can only extend another Java interface. However, an abstract class can extend another Java class as well as implement multiple Java interfaces.
- The interface can be implemented using the keyword "implements". The abstract class can be extended using the keyword "extends".
Can you declare a constructor inside an Interface?
No, you cannot have a constructor within an interface in Java. A Constructor initializes the non-static members of a particular class concerning an object, therefore:
- You can only have public, static, final variables and abstract methods.
- An interface doesn't have a constructor because all data members in an interface are public static final by default. They are constants.
- The interface has no data members that the constructor can initialize.
- To call a method, we need an object. Since the interface methods don't have a body, there is no need for calling the methods in an interface.
- Since we cannot call the interface methods, there is no need to create an object for an interface, and there is no need to have a constructor.