---Advertisement---

Java Interface

By Shiva

Published On:

---Advertisement---

Java Interface

An interface in Java is a blueprint for a class that contains abstract methods and static constants. It defines a contract that any implementing class must follow. Unlike classes, interfaces do not contain method implementationsโ€”only method signatures.

โœ” 100% abstract (before Java 8)
โœ” Can contain default and static methods (Java 8 onwards)
โœ” Supports multiple inheritance
โœ” Cannot have instance variables.
โœ” Helps achieve loose coupling


java

interface Animal {
void makeSound(); // Abstract method
}

A class can implement an interface using the implements keyword:

java

class Dog implements Animal {
public void makeSound() {
System.out.println("Dog barks");
}
}

Let’s look at a practical example to understand how interfaces work in Java:

java

// Defining an interface
interface Pet {
void play();
}

// Implementing the interface
class Dog implements Pet {
public void play() {
System.out.println("Dog is playing");
}

public static void main(String[] args) {
Pet myPet = new Dog();
myPet.play();
}
}

Output:

csharp

Dog is playing

Java does not support multiple inheritance with classes but allows it with interfaces:

java

interface Animal {
void eat();
}

interface Bird {
void fly();
}

// A class implementing multiple interfaces
class Sparrow implements Animal, Bird {
public void eat() {
System.out.println("Sparrow eats grains");
}

public void fly() {
System.out.println("Sparrow is flying");
}
}

FeatureInterfaceAbstract Class
Method ImplementationCannot have method implementations (before Java 8)Can have both abstract and concrete methods
ConstructorNot allowedAllowed
InheritanceA class can implement multiple interfacesA class can extend only one abstract class
PurposeDefines behavior (what a class should do)Defines a base class (a common blueprint)

โœ… Use an Interface when multiple classes share behavior but are unrelated.
โœ… Use an Abstract Class when classes share common functionality.


โœ” A class must implement all methods of an interface.
โœ” Interfaces support default and static methods (Java 8+).
โœ” An interface can extend multiple other interfaces.
โœ” Interface variables are public, static, and final by default.
โœ” An interface cannot implement another interface (it extends instead).


Interfaces in Java play a crucial role in achieving abstraction, loose coupling, and multiple inheritance. They help design scalable and maintainable applications. By understanding when and how to use them, developers can write more efficient and modular code.

Would you like to explore more advanced topics like functional interfaces, default methods, and real-world examples? ๐Ÿš€.

---Advertisement---

Leave a Comment