What is Interface in Java ? A Comprehensive Guide for Beginners.
A Comprehensive Guide for Beginners about Interface in Java
What is an Interface in Java?
In Simple Terms :
An interface in Java is a blueprint for a class. It defines a contract of methods that a class must implement if it claims to implement that interface. Interfaces provide a way to achieve abstraction in Java, allowing you to separate the declaration of methods from their implementation.
Why Do We Need Interfaces?
Because of three main reasons
Abstraction: Interfaces allow you to define a set of methods without providing their implementation. This is useful for creating a common set of methods that multiple classes can adhere to, promoting code reusability and consistency.
Multiple Inheritance: Unlike classes, Java supports multiple interface inheritance, meaning a class can implement multiple interfaces. This is beneficial when you want to incorporate behavior from multiple sources into a single class. we can achieve multiple Inheritance using an Interface in Java.
Contracts: Interfaces establish a contract that classes must adhere to. This helps ensure that implementing classes provides specific functionality, making it easier to reason about the behavior of objects.
How is an Interface Different from a Class?
here are some key differences :
Methods: In an interface, methods are declared but not defined (i.e., no method body). In a class, methods have both declarations and implementations.
Fields: Interfaces can only declare constants (static final fields), while classes can have instance variables.
interface Player { // declaring static constant static final int jerseyNumber = 18; }
Inheritance: A class can extend only one class (single inheritance) but can implement multiple interfaces (multiple inheritance for behavior).
Instantiation: You cannot create instances of interfaces directly. Classes that implement an interface are instantiated.
Constructor: A class can have constructors to initialize its objects, whereas Interfaces cannot have constructors because they cannot be instantiated, They are meant for defining a contract, not for creating objects.
Access Modifiers: Classes can have various access modifiers like public, private, and protected but in an interface by default, all members of an interface are implicitly public and abstract (methods) or public, static, and final (fields). You cannot use other access modifiers for interface members.
Why Do We Use Interfaces?
We use interfaces for several reasons:
Enforce Contracts: Interfaces ensure that implementing classes provide specific methods, guaranteeing a certain level of functionality.
Polymorphism: Interfaces enable polymorphism, allowing different classes to be treated uniformly if they implement the same interface.
Code Reusability: Interfaces promote code reuse by defining a common set of methods that multiple classes can implement differently.
Design by Contract: They help in adhering to the "design by contract" principle, making it clear what each class is expected to do.
Abstraction: It is used to achieve total abstraction.
Inheritance: Since Java does not support multiple inheritances in the case of class, by using an interface it can achieve multiple inheritances. Any class can extend only 1 class but can any class implement an infinite number of interfaces.
Important Points About Interfaces:
Interfaces use the
interface
keyword in Java.All methods in an interface are
public
andabstract
by default (no need to explicitly specify these modifiers).You can define constants in interfaces using
static final
variables.Classes implementing an interface must provide concrete implementations of all its methods.
interfaces don't have any constructors.
Inside the interface main method is not allowed.
Inside the interface static, final, and private methods declaration are not possible.
An interface can extend to another interface or interface (more than one interface).
We canβt create an instance(interface canβt be instantiated) of the interface but we can make the reference of it that refers to the Object of its implementing class.
Java 8 introduced default and static methods in interfaces, allowing for method implementations within interfaces.
Example Of Interface:
Let's create an example interface called Shape
:
public interface Shape {
double getArea();
double getPerimeter();
}
Now, let's create classes that implement this interface:
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
public class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
@Override
public double getPerimeter() {
return 2 * (length + width);
}
}
Some Interview Questions that could be asked about Interfaces:
What is an interface in Java, and why is it used?
- Answer: An interface is a blueprint for a class, defining a contract of methods that implementing classes must provide. It is used to achieve abstraction, multiple inheritance of behavior, and ensure adherence to a specific contract.
Can an interface have fields?
- Answer: Yes, interfaces can have constant fields (static final variables), but not instance variables.
How is an interface different from an abstract class?
- Answer: An interface can only declare method signatures, while an abstract class can declare method signatures with partial or full implementations. A class can extend only one abstract class but can implement multiple interfaces.
What is the purpose of default methods in Java interfaces?
- Answer: Default methods allow adding new methods to interfaces without breaking the existing classes that implement them. It provides backward compatibility.
What happens if a class implements an interface but does not provide implementations for all its methods?
- Answer: The class must be declared as abstract, or it will result in a compilation error. Abstract classes or concrete classes that extend it must provide implementations for all interface methods.
How does Java support multiple inheritance, and why is it important for interfaces?
- Answer: Java supports multiple interface inheritance, allowing a class to implement multiple interfaces. This is essential for combining behaviors from different sources without the issues associated with traditional multiple-class inheritance.
Congratulations! ππ» You've mastered all the essential fundamentals of Java interfaces. With this knowledge, you can confidently approach exams and interviews without any apprehension about interfaces.