Category: java
interface in Java
Published on 04 May 2026
Explanation
An interface in Java is a blueprint
of a class that is used to
achieve full abstraction.
It contains abstract methods
(by default) and constants.
A class implements
an interface using the 'implements' keyword.
Code:
interface Animal {
void sound();
}
Explanation
Interfaces are used to achieve abstraction
by
defining methods without implementation,
allowing classes to
provide their own behavior.
Code:
class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}
}
Explanation
They support multiple inheritance in Java,
meaning
a class can implement multiple interfaces.
Code:
interface A {
void methodA();
}
interface B {
void methodB();
}
class Test implements A, B {
public void methodA() {}
public void methodB() {}
}
Explanation
Interfaces are used to achieve
loose coupling,
making code more flexible and
maintainable.
Code:
interface Payment {
void pay();
}
class CreditCard implements Payment {
public void pay() {
System.out.println("
Paid using credit card");
}
}
Explanation
They are widely used in frameworks, APIs,
and for implementing design patterns
like dependency
injection and strategy pattern.
Code:
interface Database {
void connect();
}
class MySQL implements Database {
public void connect() {
System.out.println("
Connected to MySQL");
}
}