A2oz

Which keyword is used in Java to implement inheritance?

Published in Java Programming 1 min read

The keyword used in Java to implement inheritance is extends.

How Inheritance Works in Java:

  • extends keyword: This keyword is used to specify that a class inherits properties and methods from another class.
  • Parent class (Superclass): The class from which inheritance is derived.
  • Child class (Subclass): The class that inherits from the parent class.

Example:

class Animal { // Parent class
    public void makeSound() {
        System.out.println("Generic animal sound");
    }
}

class Dog extends Animal { // Child class
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}

In this example, the Dog class inherits from the Animal class. The Dog class can access and use all the methods and properties of the Animal class, including the makeSound() method. However, the Dog class can also override the makeSound() method to provide its own specific sound.

Benefits of Inheritance:

  • Code reusability: Avoids writing the same code multiple times.
  • Hierarchical structure: Organizes code into a logical hierarchy.
  • Polymorphism: Allows objects of different classes to be treated as objects of a common type.

Related Articles