Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java extends Keyword
Usage and Examples



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

What You Cannot Do



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M