In object-oriented programming (OOP), an interface is a fundamental concept that defines a contract or a set of abstract methods that a class must implement. An interface, in essence, specifies a list of methods that a class that implements the interface must provide. Interfaces do not contain any actual method implementations; they only declare the method signatures (names, parameters, and return types).
Overview
- What is an interface?
- Creating and using an interface.
- Extending interfaces
- Implementing multiple interfaces.
- What are abstract classes?
- Creating and Using abstract classes.
- Differences between abstract classes and interface
What is an interface?
- It is a mechanism by which Java somewhat achieves multiple inheritance.
- It is a system using which unrelated objects interact with each other.
- An interface is a class where all the fields are public,static & final and all the methods are public & abstract.
- But it is different from multiple inheritance
Creating and using an interface
interface
extends
//statement block
}
class implements <
InterfaceName >{
//statement block
Extending interfaces
- An interface, unlike other classes can extend multiple interfaces.
- A class implementing an extended interface has to implement the methods of both the interface, as well as its ancestors.
Implementing multiple interfaces
- A class can choose to implement multiple interfaces.
- It then has to implement all the methods defined in all the chosen interfaces.
- Helpful in spreading concept of multiple inheritance, where a class chooses to pick multiple behavioral patterns
// Define an interface
interface Shape {
double calculateArea();
// Abstract method
double calculatePerimeter();
// Abstract method
}
// Implement the interface in a class
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
In this example, the Shape
interface defines two abstract methods: calculateArea()
and calculatePerimeter()
. The Circle
class implements the Shape
interface by providing concrete implementations for these methods.
Interfaces are a fundamental concept in OOP that promotes code reusability, maintainability, and polymorphism, making them a powerful tool in software development.