Junior — Middle
What is the difference between the keywords 'implements' and 'extends' in Java, and in which cases are they used?
sobes.tech AI
Answer from AI
In Java, the keywords extends and implements are used for different purposes:
-
extendsis used for class inheritance or class extension. One class can inherit from another class, gaining its fields and methods. -
implementsis used for interface implementation. A class commits to implementing all methods of the interface.
Examples:
// Class inheritance
class Animal {
void eat() { System.out.println("Eating"); }
}
class Dog extends Animal {
void bark() { System.out.println("Barking"); }
}
// Interface implementation
interface Runnable {
void run();
}
class Athlete implements Runnable {
public void run() {
System.out.println("Running");
}
}
Important:
- A class can inherit only one class (
extends), but can implement multiple interfaces (implements). - Interfaces can inherit from each other using
extends, but classes cannot.
Use extends when creating a specialized class based on an existing one, and implements when a class needs to adhere to a specific contract (interface).