extends
Keyword in Java
The extends
keyword in Java allows one class to inherit the fields and methods of another class. This is Java's way of implementing single inheritance. Inheritance is one of the core pillars of object-oriented programming (OOP), and extends
is the gateway to it.
What Does extends
Do?
When one class extends
another, it means the child class (also called the subclass or derived class) gains all the accessible properties and behaviors (methods) of the parent class (also called the superclass).
Syntax
class ParentClass {
// fields and methods
}
class ChildClass extends ParentClass {
// additional fields and methods
}
Example 1: Simple Inheritance
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.makeSound(); // inherited method
d.bark(); // Dog's own method
}
}
Animal makes a sound
Dog barks
Explanation
In this example, the class Dog
inherits the method makeSound()
from Animal
. It can use both its own methods and the ones from its parent.
Example 2: Method Overriding
class Animal {
void makeSound() {
System.out.println("Generic animal sound");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Cat(); // polymorphism
a.makeSound();
}
}
Meow
Explanation
The subclass Cat
overrides the makeSound()
method. Even though the reference is of type Animal
, the actual object is Cat
. So, the overridden method in Cat
is executed. This is dynamic method dispatch at play.
Example 3: Inheriting Fields
class Vehicle {
int speed = 60;
}
class Car extends Vehicle {
String brand = "Toyota";
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
System.out.println(car.speed); // inherited field
System.out.println(car.brand); // Car's own field
}
}
60
Toyota
Best Practices
- Use
extends
when there's a clear "is-a" relationship. For example, aDog
is anAnimal
. - Favor composition over inheritance when the relationship isn't so clear-cut.
- Always annotate overridden methods with
@Override
to catch mistakes at compile time.
What You Cannot Do
- Java supports only single inheritance using classes. A class cannot extend more than one class.
- To achieve multiple inheritance-like behavior, use interfaces with the
implements
keyword.