An interface in Java is a blueprint of a class.
It contains:
- method declarations
- constants
But usually it does not contain full method implementation.
Interface tells:
- What to do
- not
- How to do
Syntax
interface Animal {
void sound();
}
Here:
-
Animalis interface -
sound()has no body
Implementing Interface
class Dog implements Animal {
public void sound() {
System.out.println("Bark");
}
}
implements keyword is used.
Why use Interface?
1. Achieve Abstraction
Hide internal details.
void sound();
Only rule is given.
2. Multiple Inheritance
Java does not support:
class A extends B, C
But interface allows multiple inheritance.
interface A {}
interface B {}
class Test implements A, B {}
Variables in interface are:
Automatically:
public static final
Example:
interface Test {
int x = 10;
}
Same as:
public static final int x = 10;
Methods are automatically:
public abstract
Top comments (0)