Which of the following statements is true about Java interfaces?a)An i...
In Java, a class can implement multiple interfaces by using the implements keyword followed by the interface names separated by commas.
View all questions of this test
Which of the following statements is true about Java interfaces?a)An i...
Explanation:
Interfaces in Java are a way to define a contract or a set of rules that a class must adhere to. They are similar to classes but they cannot be instantiated directly. Instead, they are implemented by classes that provide the implementation for the methods defined in the interface.
A class can implement multiple interfaces:
One of the key features of Java interfaces is that a class can implement multiple interfaces. This means that a class can provide implementation for the methods defined in multiple interfaces. By implementing multiple interfaces, a class can inherit and provide implementation for a wide range of behaviors.
Example:
Let's consider an example where we have two interfaces: Printable and Displayable. The Printable interface defines a method called print, and the Displayable interface defines a method called display. We can have a class called Document that implements both interfaces, providing implementation for both the print and display methods.
```
interface Printable {
void print();
}
interface Displayable {
void display();
}
class Document implements Printable, Displayable {
public void print() {
// implementation for print method
}
public void display() {
// implementation for display method
}
}
```
In this example, the Document class implements both the Printable and Displayable interfaces. This means that the Document class must provide implementation for both the print and display methods. By implementing multiple interfaces, the Document class can exhibit both the behavior of being printable and displayable.
Advantages of implementing multiple interfaces:
Implementing multiple interfaces allows for greater flexibility and reusability in the code. It enables classes to inherit and provide implementation for a variety of behaviors from different interfaces. This promotes code modularity and helps in achieving better code organization.
It is worth mentioning that while a class can implement multiple interfaces, an interface cannot extend multiple classes. In Java, a class can only extend one class, but it can implement multiple interfaces.