In Java, `extend` and `implement` are keywords used for inheritance and interface implementation, respectively. Here's the difference between the two:
1. `extend`:
- Used to inherit from a class.
- A class can extend only one class (single inheritance).
- The subclass inherits all the public and protected methods and fields of the superclass.
- The subclass can add new methods and fields, and also override the methods of the superclass.
Example:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks");
}
}
2. `implement`:
- Used to implement an interface.
- A class can implement multiple interfaces.
- The implementing class must provide implementations for all the methods declared in the interface.
- Interfaces can only have method signatures and constants (Java 8 and earlier). From Java 9 onwards, interfaces can have private methods and default methods (methods with a default implementation).
Example:
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Dog barks");
}
}
In summary, `extend` is used for class inheritance, while `implement` is used for implementing interfaces.