Interface in Java
Interface in java
Definiton :
Interface is a collection of abstract methods and constants (i.e. static and final fields). It is used to achieve complete abstraction.
- Interface in non- primitive datatype in java.
- An interface is a reference type in Java that defines a contract for classes .
- An interface in Java is a blueprint for a class.
- Interfaces are widely used in Java for defining contracts, ensuring code reusability, and enabling loose coupling between components in object-oriented programming.
- Use the interface keyword to declare an interface.
- Syntax:
interface InterfaceName
{
// interface body
}
- All variables declared in an interface are public, static, and final.
- All methods are implicitly public and abstract (no method body) in the interface.
- Interfaces can also have static methods that can be called using the interface name.
- An interface does not contain any implementation for its methods; it only declares their signatures.
- Classes can implement an interface using the `implements` keyword.
- A class implementing an interface must provide concrete implementations for all the methods declared in the interface, as well as in any parent interfaces that the interface extends.
- Syntax:
class ClassName implements InterfaceName
{
// class body
}
Multiple Inheritance via Interfaces:
- Java supports multiple inheritance through interfaces since a class can implement multiple interfaces.
- A class can implement multiple interfaces but extend only one class (single inheritance rule).
- Interfaces can extend other interfaces, forming an interface hierarchy.
- A class implementing a derived interface must provide implementations for all methods in both interfaces.
Interface vs. Abstract Class:
Unlike abstract classes, interfaces cannot have constructors and cannot be directly instantiated. However, a class can implement multiple interfaces, while it can extend only one abstract class.
Differenece between class & interface
An interface is declared like a class but the only difference is that it contains only final variables and method declarations. It is a fully abstract class.
Comments
Post a Comment