Java

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 of Animal.
  • Dog inherits all non-private methods and fields of Animal.
  • You can call makeSound() using a Dog 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 interface A.
  • A class implementing B must implement both methodA() and methodB().

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: