Example
An interface serves as an abstract structure for grouping related methods with unimplemented bodies:
To utilize the interface methods, another class must “implement” it, akin to inheritance, using the implements keyword instead of extends. The implementation of the interface method is provided by the implementing class.
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out .println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out .println("Zzz");
}
}
class MyMainClass {
public static void main(String[] args ) {
Pig myPig = new Pig(); // Create a Pig object
myPig .animalSound();
myPig .sleep();
}
}
|
Definition and Usage
The interface keyword signifies the declaration of a distinct class type, exclusively comprising abstract methods.
To utilize the interface methods, another class must “implement” it, akin to inheritance, using the implements keyword instead of extends. The implementing class furnishes the implementation details for the interface method.
Notes on Interfaces:
- Objects cannot be instantiated directly from an interface; for instance, in the provided example, creating an “Animal” object within MyMainClass is not feasible.
- Interface methods lack a body; the implementing class provides the implementation details.
- Upon implementation of an interface, all its methods must be overridden.
- Interface methods are inherently abstract and public.
- Interface attributes are inherently public, static, and final.
- An interface cannot include a constructor, as it doesn’t facilitate object creation.
Why And When To Use Interfaces?
To ensure security by concealing specific details and revealing only the essential aspects of an object (interface), Java utilizes interfaces.
Java doesn’t enable “multiple inheritance” (where a class inherits from more than one superclass). Nonetheless, this can be achieved through interfaces, as a class can implement multiple interfaces. Remember: To implement multiple interfaces, separate them with commas (as illustrated below).
|
Multiple Interfaces
To implement multiple interfaces, list them separated by commas.
Example
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
// DemoClass "implements" FirstInterface and SecondInterface
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out .println("Some text..");
}
public void myOtherMethod() {
System.out .println("Some other text...");
} }
class MyMainClass {
public static void main(String[] args ) {
DemoClass myObj = new DemoClass();
myObj .myMethod();
myObj .myOtherMethod();
}
}
|