Search⌘ K
AI Features

Mastering Interfaces

Explore Java interfaces to understand how they define behavioral contracts using abstract, default, and static methods. Learn the role of marker interfaces and how to implement custom comparators with modern Java methods. This lesson helps you grasp interface concepts essential for clean and maintainable Java code.

We'll cover the following...

Let's explore the core concepts of interfaces and how they define contracts in Java through these commonly asked interview questions.

AI Powered
Saved
10 attempts left
Reset
Question

What is an interface in Java?

You have 10 attempts to answer.
AI Powered
Saved
10 attempts left
Reset
Question

What is the difference between an interface and an abstract class in Java?

You have 10 attempts to answer.
AI Powered
Saved
10 attempts left
Reset
Question

When should we use an abstract class and when should we use an interface?

You have 10 attempts to answer.
AI Powered
Saved
10 attempts left
Reset
Question

What are default and static methods of an interface?

You have 10 attempts to answer.

Let's look at an interface that utilizes both default and static methods.

Java
public class Demonstration {
public static void main(String[] args) {
PersonActions person = new Person();
person.sayHello();
person.sayBye();
PersonActions.printTotalPossibleActions();
}
}
interface PersonActions {
void sayHello();
default void sayBye() {
System.out.println("Say bye in English and override method for other languages.");
}
static void printTotalPossibleActions() {
System.out.println("Total possible actions = 2");
}
}
class Person implements PersonActions {
@Override
public void sayHello() {
System.out.println("Hello!");
}
}
  • Lines 4–9: The main method creates a Person object through the PersonActions ...