Interface
Java Interface Overview:
An interface in Java is a fully abstract class that contains abstract methods. Interfaces are created using the
interface
keyword and cannot be instantiated. They provide a set of rules (abstract methods) that implementing classes must follow.Here,
Language
is an interface with abstract methodsgetType()
andgetVersion()
.Implementing an Interface:
Like abstract classes, interfaces cannot be directly instantiated. Other classes must implement the interface using the
implements
keyword. An example demonstrates the implementation of an interface namedPolygon
.Output:
The area of the rectangle is 30
Implementing Multiple Interfaces:
Java allows a class to implement multiple interfaces, providing flexibility in design.
Extending an Interface:
Interfaces can extend other interfaces using the
extends
keyword, creating a hierarchy of interfaces.Default Methods in Interfaces:
Introduced in Java 8, default methods allow the addition of methods with implementation inside an interface. These methods are inherited like ordinary methods.
Default methods help avoid issues when adding new methods to existing interfaces, as implementing classes automatically inherit the new method.
Private and Static Methods in Interface:
Java 8 introduced static methods inside an interface. With Java 9, private methods are also supported. Static methods can be accessed using the interface reference.
Practical Example of Interface:
A practical example illustrates the use of an interface named
Polygon
with a default method for calculating perimeter and an abstract method for calculating the area. TheTriangle
class implements thePolygon
interface.Output:
In this example,
Polygon
is an interface with a default method for perimeter calculation, andTriangle
provides an implementation for the area calculation.
Last updated