We’re going to delve into the world of Java, focusing on two key concepts: interfaces and abstract classes. While these aren’t data types in the traditional sense, they play a crucial role in how we structure and design our Java applications. We’ll explore what interfaces and abstract classes are, how they differ, and why they are essential in Java programming.
Interfaces in Java are a set of abstract and public methods we want our classes to implement. It is the blueprint of a class and contains static constants and abstract methods.
Interfaces are used to achieve abstraction and implement multiple inheritance.
An interface is a set of abstract methods you would want your class to implement. These methods are public and abstract by default(you don’t have to explicitly use the “abstract” keyword), and any class implementing your interface will need to provide implementations of those methods.
What are Interfaces in Java?
In Java, an interface is an abstract data type that defines a set of abstract methods for classes to implement. It’s akin to a contract or a blueprint for a class. Interfaces are unique because they can have only constants and method declarations. From Java 8 onwards, interfaces can also have default and static methods with a defined body.Java Interface also represents the IS-A relationship.
How to Declare and Use an Interface in Java?
In Java, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. An interface cannot contain instance fields. Interfaces are used to define a contract for classes that implement them, specifying what methods they must implement.
Declaring an Interface
public interface MyInterface {
// Constant declaration
int MY_CONSTANT = 10;
// Method signature declaration (no method body)
void myMethod();
// You can also declare static methods in interfaces
static void staticMethod() {
System.out.println("This is a static method in the interface.");
}
// You can declare default methods as well (with a method body)
default void defaultMethod() {
System.out.println("This is a default method in the interface.");
}
}
Java
Implementing an Interface
public class MyClass implements MyInterface {
// Implementing the method defined in the interface
@Override
public void myMethod() {
System.out.println("Implemented method in MyClass");
}
// You can provide your own additional methods
public void anotherMethod() {
System.out.println("Another method in MyClass");
}
}
Java
Using the Interface and Implementing Class
public class Main {
public static void main(String[] args) {
// You can create an instance of the implementing class
MyClass obj = new MyClass();
// Call the method implemented from the interface
obj.myMethod(); // Output: Implemented method in MyClass
// Call default method from the interface
obj.defaultMethod(); // Output: This is a default method in the interface.
// Accessing a constant from the interface
System.out.println(MyInterface.MY_CONSTANT); // Output: 10
// Call a static method from the interface
MyInterface.staticMethod(); // Output: This is a static method in the interface.
// You can also use polymorphism to treat the object as the interface type
MyInterface interfaceObj = new MyClass();
interfaceObj.myMethod(); // Output: Implemented method in MyClass
}
}
Java
This example demonstrates how to declare an interface, implement it in a class, and use the interface methods and constants.
Why Use a Java Interface?
- Abstraction: Interfaces allow you to define a contract specifying the behavior that implementing classes must adhere to, without providing any implementation details. This promotes abstraction by focusing on what objects can do rather than how they do it.
- Multiple Inheritance: Java classes can only extend one superclass, but they can implement multiple interfaces. This enables a form of multiple inheritance, where a class can inherit behavior from multiple sources by implementing multiple interfaces.
- Polymorphism: Interfaces facilitate polymorphism, allowing objects to be treated as instances of their interface type. This enables greater flexibility in programming, as objects can be manipulated based on their common interface rather than their specific implementation.
- Code Reusability: Interfaces promote code reusability by defining a set of methods that can be implemented by multiple classes. This reduces code duplication and promotes modular design by separating concerns.
- Interoperability: Interfaces provide a common contract that can be implemented by different classes. This promotes interoperability by allowing objects of different classes to be treated uniformly based on their shared interface.
- Encapsulation: Interfaces help in encapsulating the implementation details of classes, as they only expose the methods specified in the interface. This promotes encapsulation by hiding internal details and reducing coupling between components.
- Testing and Mocking: Interfaces facilitate unit testing and mocking by allowing you to create mock implementations of interfaces for testing purposes. This enables easier testing of classes by substituting real implementations with mock objects that adhere to the interface.
- Future Extensibility: Interfaces provide a clear separation between the contract and its implementations, making it easier to extend or modify the behavior of classes in the future without impacting the clients of those classes.
Implementing Multiple Interfaces in Java
Example
// Define two interfaces
interface Interface1 {
void method1();
}
interface Interface2 {
void method2();
}
// Implement both interfaces in a single class
class MyClass implements Interface1, Interface2 {
@Override
public void method1() {
System.out.println("Implementation of method1");
}
@Override
public void method2() {
System.out.println("Implementation of method2");
}
}
public class Main {
public static void main(String[] args) {
// Create an instance of MyClass
MyClass myClass = new MyClass();
// Call methods from both interfaces
myClass.method1();
myClass.method2();
}
}
Java
Output
Implementation of method1
Implementation of method2
Java
Extending Interfaces in Java
Example
// Define a base interface
interface BaseInterface {
void baseMethod();
}
// Define an extended interface that extends BaseInterface
interface ExtendedInterface extends BaseInterface {
void extendedMethod();
}
// Implement the extended interface in a class
class MyClass implements ExtendedInterface {
@Override
public void baseMethod() {
System.out.println("Implementation of baseMethod");
}
@Override
public void extendedMethod() {
System.out.println("Implementation of extendedMethod");
}
}
public class Main {
public static void main(String[] args) {
// Create an instance of MyClass
MyClass myClass = new MyClass();
// Call methods from both interfaces
myClass.baseMethod();
myClass.extendedMethod();
}
}
Java
Output
Implementation of baseMethod
Implementation of extendedMethod
Java
Types of interfaces in Java?
Types of interfaces in Java are mentioned below:
- Functional Interface
- Marker interface
In Java, interfaces can be categorized into several types:
Marker Interfaces
These interfaces don’t declare any methods. They are used to mark classes that implement them for special treatment by Java runtime or other tools. Examples include Serializable
and Cloneable
.
Functional Interfaces
These interfaces have only one abstract method and can be used as lambda expressions or method references. Examples include Runnable
and Comparator
.
Difference Between Class and Interface
Although Class and Interface seem the same there have certain differences between Classes and Interface. The major differences between a class and an interface are mentioned below:
Class | Interface |
In class, you can instantiate variables and create an object. | In an interface, you can’t instantiate variables and create an object. |
A class can contain concrete (with implementation) methods | The interface cannot contain concrete (with implementation) methods. |
The access specifiers used with classes are private, protected, and public. | In Interface only one specifier is used- Public. |
Note: Implementation – To implement an interface, we use the keyword implements
Difference Between abstraction and Interface
Abstract Class | Interface |
1) Abstract class can have abstract and non-abstract methods. | Interface can have only abstract methods. Since Java 8, it can have default and static methods also. |
2) Abstract class doesn’t support multiple inheritance. | Interface supports multiple inheritance. |
3) Abstract class can have final, non-final, static and non-static variables. | Interface has only static and final variables. |
4) Abstract class can provide the implementation of interface. | Interface can’t provide the implementation of abstract class. |
5) The abstract keyword is used to declare abstract class. | The interface keyword is used to declare interface. |
6) An abstract class can extend another Java class and implement multiple Java interfaces. | An interface can extend another Java interface only. |
7) An abstract class can be extended using keyword “extends”. | An interface can be implemented using keyword “implements”. |
8) A Java abstract class can have class members like private, protected, etc. | Members of a Java interface are public by default. |
9)Example:public abstract class Shape{public abstract void draw();} | Example:public interface Drawable{void draw();} |
Simply, the abstract class achieves partial abstraction (0 to 100%) whereas the interface achieves fully abstraction (100%).
Advantages of Interfaces in Java
The advantages of using interfaces in Java are as follows:
- Without bothering about the implementation part, we can achieve the security of the implementation.
- In Java, multiple inheritances are not allowed, however, you can use an interface to make use of it as you can implement more than one interface.
Conclusion
Java interfaces provide a powerful mechanism for achieving abstraction, polymorphism, and contract-based programming in Java. They allow us to define a set of methods that must be implemented by classes that claim to adhere to a certain contract, without specifying how those methods are implemented. Interfaces support multiple inheritance, enabling a class to implement multiple interfaces. Moreover, interfaces facilitate loose coupling and flexibility in software design by allowing different implementations to be easily interchanged as long as they adhere to the interface contract. Through various types of interfaces, including marker interfaces, functional interfaces, SAM interfaces, and normal interfaces, Java offers a versatile toolset for building robust, modular, and maintainable software systems.
FAQs
1. What is a Java interface?
A Java interface is a reference type similar to a class that can contain only abstract methods, default methods, static methods, and constant variables. It defines a contract for classes to implement, without specifying how those methods are implemented.
2. How do interfaces differ from classes in Java?
Interfaces in Java cannot be instantiated directly, whereas classes can be. Additionally, interfaces can’t contain instance variables (except constants), constructors, or non-public members like classes. Classes can implement multiple interfaces, but they can only extend one class.
3. Can a class implement multiple interfaces in Java?
Yes, a class can implement multiple interfaces in Java. This feature allows for multiple inheritance of type, enabling a class to exhibit behavior from multiple sources.
4. What are marker interfaces in Java?
Marker interfaces are interfaces without any methods. They serve as markers to the compiler or runtime environment for special treatment. Examples include Serializable
, Cloneable
, and RandomAccess
.