Interface in Java
An interface is a type definition block in Java that is completely abstract. It is used to achieve full abstraction and to define a contract that implementing classes must follow.
Key Points
- An interface is declared using the interface keyword.
- An interface can contain:
✓public static final variables (constants)
✓public abstract methods (instance methods)
- An interface cannot be instantiated (object creation is not allowed).
- An interface can extend another interface using the extends keyword.
- A class can implement an interface using the implements keyword.
- An interface cannot extend a class.
- An interface supports complete abstraction because it contains only abstract methods.
- An interface supports multiple inheritance
Example
int AGE = 5; // public static final by default
void sound(); // public abstract by default
class Dog implements Animal {
System.out.println("Dog barks");
Multiple Inheritance Using Interface
class C implements A, B {
System.out.println("Show method");
System.out.println("Display method");
Contracts Between Interface and Implementing Class
Contract 1
If a class implements an interface, then the class must provide implementations for all abstract methods declared in the interface.
👉 Implementation means method overriding
Contract 2
If a class implements an interface but does not provide implementations for the abstract methods, then the class must be declared abstract.
abstract class Sample implements Animal {
// No implementation provided
Important Notes
- All methods in an interface are public and abstract by default.
- All variables in an interface are public, static, and final by default.
- Interfaces are widely used to achieve loose coupling and multiple inheritance in Java.
Comments
Post a Comment