In Java, an interface is a reference type, similar to a class, that can contain only constant declarations, method signatures (without the method body), and default methods (with a default implementation) since Java 8.
Interfaces provide a way to achieve abstraction, allowing us to define a contract for classes that implement the interface must adhere to.
We define an interface using the "interface" keyword followed by the interface name and its contents.
Interfaces can contain method declarations and constant declarations, but no instance variables.
interface Animal { void sound(); // Method signature (abstract method) }
A class can implement one or more interfaces by using the "implements" keyword.
interface Animal { void sound(); // Method signature (abstract method) default void displayNickName(String nickName) { System.out.println("Nick Name: " + nickName); } } // Concrete subclass implementing the Animal Interface class Dog implements Animal { @Override public void sound() { System.out.println("Woof!"); } } public class Main { public static void main(String[] args) { // Creating instances of Dog Dog dog = new Dog(); // Calling methods dog.sound(); // Calling Interface Method dog.displayNickName("tyler"); } }
When a class implements an interface, it must provide implementations for all the methods declared in the interface.
Woof! Nick Name: tyler
interface Pet extends Animal { void play(); // Additional method in the extended interface }
An interface can extend one or more other interfaces using the "extends" keyword.
An interface that extends another interface inherits all the methods and constants declared in the parent interface(s).
interface Animal { void sound(); // Abstract method default void eat() { // Default method System.out.println("Eating..."); } }
Starting from Java 8, interfaces can have default methods, which provide a default implementation for the method.
interface Animal { static void walk() { // Static method System.out.println("Walking..."); } }
Default methods allow us to add new methods to existing interfaces without breaking the classes that implement them.
Note: If we don't declare the `default keyword` then the method by default is declared as an `abstract method` and the `abstract method` can't have the `body`.
Interfaces can also have static methods, which are similar to default methods but are marked as "static". Static methods in interfaces provide utility methods related to the interface.
Interfaces play a crucial role in Java programming, especially in achieving abstraction, multiple inheritance of type, and providing a contract for implementing classes.
They are widely used in various Java APIs and frameworks to define contracts that classes must adhere to, promoting code reuse and modularity.