Interfaces in Java provide another way to achieve abstraction. An interface is like a completely "abstract class" because it contains only abstract methods and constants (without any implementation). It is a blueprint or contract for classes to follow. It defines a set of methods and constants that any class implementing the interface must provide.
Example:
interface IShape
{
double PI = 3.14159; // constant
void draw(); // Interface method for drawing a shape
double calculateArea(); // Interface method for calculating the shape's area
}
In this example, the `IShape` interface declares two abstract methods: `draw()` and `calculateArea()` and a constant 'PI'. Any class that implements this interface must provide concrete implementations for these two methods.
It's a good practice to name interfaces with an "I" at the beginning, making it easier to distinguish them from regular classes.
NOTE: By default, the members of an interface are abstract and public. And the constant is always public, static, and final. (alert-success)
To implement an interface, a class needs to use the `: operator` and mention the interface name after its class name:
Example:
class Circle implements IShape
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public void draw()
{
System.out.println("Drawing a circle");
}
public double calculateArea()
{
// Implementation for calculating the area of a circle
return PI * radius * radius;
}
}
Here, the `Circle` class implements the `IShape` interface. It provides the necessary implementation for the `draw()` and `calculateArea()` methods. The interface ensures that any class implementing it adheres to these method signatures.
NOTE: Unlike regular methods, there's no need to use the "override" keyword when implementing interface methods. (alert-success)
Unlike C++, Java does not support multiple inheritance for classes, but it does allow the implementation of multiple interfaces.
Multiple Inheritance with Interface:
Multiple inheritance allows a sub class to inherit from multiple super interfaces. This means that the sub class can combine the features and behaviors of multiple super interfaces.
Example:
interface ISuper1
{
// Super interface 1 members
}
interface ISuper2
{
// Super interface 2 members
}
class Sub : ISuper1, ISuper2
{
// Sub class members
}