Understanding Java Interfaces: Achieving Abstraction in Programming
Learn about Java interfaces, a powerful feature that allows you to achieve abstraction by grouping related methods without implementation. Discover how to use interfaces to enhance code organization and facilitate multiple inheritance in your Java applications.
Java Interface
Interfaces in Java provide a way to achieve abstraction, allowing you to group related methods without providing their implementation.
Example
Syntax
// interface
interface Animal {
public void animalSound(); // interface method (no body)
public void run(); // interface method (no body)
}
To use interface methods, another class must "implement" the interface using the implements
keyword:
Example
// Interface
interface Animal {
public void animalSound(); // interface method (no body)
public void sleep(); // interface method (no body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
public void sleep() {
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Output
The pig says: wee wee
Zzz
Notes on Interfaces:
- Interfaces cannot be used to create objects.
- Interface methods do not have a body; the body is provided by the implementing class.
- When implementing an interface, you must override all of its methods.
- Interface methods are abstract and public by default.
- Interface attributes are public, static, and final by default.
- Interfaces cannot contain a constructor.
Why And When To Use Interfaces?
- To achieve security by hiding certain details and showing only the essential parts (interface).
- To achieve multiple inheritance since Java supports only single inheritance from a superclass but allows implementing multiple interfaces.
Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
Example
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
Output
Some text..
Some other text...