Java extends Keyword
Java extends
Keyword
The Java extends
keyword is used to create a subclass, allowing one class to inherit the properties and methods of another (superclass). It supports code reuse and establishes an “is-a” relationship between classes.
extends
in Class Inheritance
When one class inherits from another class, it uses extends
.
class Animal {
void makeSound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
Explanation:
Dog
is a subclass ofAnimal
.Dog
inherits all non-private methods and fields ofAnimal
.- You can call
makeSound()
using aDog
object.
extends
in Interface Inheritance
Interfaces can also extend other interfaces using extends
.
interface A {
void methodA();
}
interface B extends A {
void methodB();
}
Explanation:
- Interface
B
inherits all methods from interfaceA
. - A class implementing
B
must implement bothmethodA()
andmethodB()
.
Key Points
- A class can only extend one other class (single inheritance).
- An interface can extend multiple interfaces.
interface A {}
interface B {}
interface C extends A, B {} // valid
Note: extends
is not used when a class implements an interface — we use implements
instead.
class MyClass implements Runnable {
public void run() {
System.out.println("Running...");
}
}
Java Tutorials
Java Tutorial on this website: