Object-Oriented Programming – Interfaces
Object-Oriented Programming – Interfaces
Interfaces
Understanding Interfaces in Java
What is an Interface?
• An interface is a contract that a class agrees to
follow.It contains method signatures without
implementations.The class that implements
the interface must provide implementation for
all its methods.
interface Animal {
void makeSound(); // abstract method
}
Key Features of Interfaces
• All methods are public and abstract by default.
• Interfaces support multiple inheritance.
• A class uses the implements keyword to
inherit from an interface.
• Variables in interfaces are public static final by
default.
Example
interface Animal {
void makeSound(); // Abstract method
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Bark");
}
}
Purpose Defines a contract for what a class Provides partial abstraction and
can do, without saying how allows defining default behavior
Purpose interface, implements abstract, extends
interface Showable {
void show();
}
class Document implements Printable, Showable {
public void print() {
System.out.println("Printing Document");
}