In the realm of object-oriented programming, inheritance is a fundamental concept that allows classes to acquire properties and methods from other classes. In Java, this is achieved using a specific keyword. But which one?

Before diving into the keyword, let's briefly understand why inheritance is crucial. It promotes code reusability, establishes 'is-a' relationships, and enables polymorphism. Now, let's find out how to inherit a class in Java.

The Keyword: 'extends'
The keyword you're looking for is 'extends'. It's used to indicate that a class is inheriting from another class.

Here's a simple syntax to illustrate this:
```java class ParentClass { // properties and methods } class ChildClass extends ParentClass { // properties and methods } ```
Using 'extends' for Inheritance

In the example above, 'ChildClass' is inheriting from 'ParentClass'. This means 'ChildClass' can access all the public and protected properties and methods of 'ParentClass'.
Here's a simple example:
```java class Animal { void eat() { System.out.println("Eating"); } } class Dog extends Animal { void bark() { System.out.println("Barking"); } } ```
Inheriting Constructors

Java also allows you to inherit constructors using the 'super' keyword. This is useful when you want to call a parent class constructor from a child class.
Here's an example:
```java class Parent { Parent() { System.out.println("Parent constructor"); } } class Child extends Parent { Child() { super(); // Calling parent constructor System.out.println("Child constructor"); } } ```
Inheritance and Access Modifiers

Inheritance in Java is subject to access modifiers. A child class can only access the public and protected members of its parent class.
Here's a quick rundown:




















- Public: Accessible everywhere, including child classes.
- Protected: Accessible within the same package and subclasses, even in other packages.
- Default (no modifier): Accessible within the same package.
- Private: Only accessible within the same class.
Protected Access Modifier
The 'protected' access modifier is particularly useful in inheritance. It allows child classes to access the parent's methods and properties, even if they're in different packages.
Here's an example:
```java // In package1 class Parent { protected void display() { System.out.println("Parent display"); } } // In package2 class Child extends Parent { void test() { display(); // Accessing protected method } } ```
In conclusion, the keyword to inherit a class in Java is 'extends'. It's a powerful tool that enables code reusability and establishes relationships between classes. As you delve deeper into Java programming, you'll find inheritance to be an essential concept that unlocks the full potential of object-oriented programming.