Home Resource Centre Extends Keyword In Java | Syntax, Applications & More (+Examples)

Extends Keyword In Java | Syntax, Applications & More (+Examples)

In Java, inheritance is a powerful concept that allows one class to acquire the properties and methods of another. At the heart of this lies the extends keyword, which plays a crucial role in defining relationships between classes. By using extends, we can create a subclass that inherits from a parent class, promoting code reuse and modularity.

In this article, we'll explore the extends keyword in Java, its syntax, usage, and significance in object-oriented programming. From basic examples to advanced scenarios, we will uncover how extends enhances code structure and flexibility while adhering to the principles of inheritance.

Understanding The extends Keyword In Java?

The extends keyword in Java programming is used to establish inheritance between two classes. When a class uses extends, it means it is inheriting (or "borrowing") properties and methods from another class, called the parent or superclass. This allows the new class, called the child or subclass, to reuse existing code and add its own features.

Real-Life Analogy:

Imagine a general blueprint for a car. This blueprint defines common features like wheels, engine, and seats. Now, if you want to design a sports car, you don't need to start from scratch. You can extend the car's blueprint to inherit its features and add new ones, like a turbo engine or a sporty design.

Thus:

  • The general car blueprint is the superclass.
  • The sports car blueprint is the subclass that extends the superclass.

Syntax Of extends Keyword In Java

class Superclass {
    // Fields and methods of the superclass
}

class Subclass extends Superclass {
    // Additional fields and methods of the subclass
}

Here: 

  • Extends: It establishes an inheritance relationship between two classes. Indicates that the subclass is inheriting from the superclass.
  • Superclass: The base class that provides common features to be inherited.
  • Subclass: The derived class that inherits from the superclass using extends.

Use Of extends Keyword In Java

The extends keyword in Java is primarily used to create an inheritance relationship between two classes or interfaces. It allows one class or interface to inherit the properties and methods of another, promoting code reuse and enhancing modularity. Some of the key uses of the extends keyword in Java are as follows:

  • Single Inheritance (Class Inheritance): A class can inherit from another class using the extends keyword. This allows the derived (child) class to reuse the code in the base (parent) class. Java only supports single inheritance for classes, meaning one class can extend only one other class directly.
  • Multiple Inheritance through Interfaces: Interfaces can extend multiple interfaces using the extends keyword, allowing for multiple inheritance of behavior (methods). This helps in achieving multiple inheritance in Java (which is not possible with classes directly).
  • Method Overriding: When a subclass inherits a method from the superclass, it can override that method to provide a more specific implementation. The extends keyword establishes the inheritance link, making overriding possible.

Using Java extends To Implement Single Inheritance

Single Inheritance occurs when one class (the derived or child class) inherits from another class (the base or parent class). The extends keyword in Java is used to establish this relationship, allowing the child class to access the properties and methods of the parent class.

Code Example: 

Output: 

This animal eats food.
The dog barks.

Explanation: 

In the above code example-

  1. We start by defining a base class Animal that represents a generic parent class with a method eat() that outputs "This animal eats food."
  2. Then, we create a derived class Dog that extends the Animal class using the extends keyword. This establishes an inheritance relationship.
  3. In the Dog class, we add a new method bark() that outputs "The dog barks." This method is specific to the Dog class.
  4. Inside the Main class, we define the main() method, which is the entry point of our program.
  5. We then create an object myDog of the Dog class, which allows us to access methods from both the Dog class and the inherited methods from the Animal class.
  6. By calling myDog.eat(), we invoke the eat() method from the base Animal class, showcasing inheritance.
  7. By calling myDog.bark(), we invoke the bark() method specific to the Dog class, demonstrating the addition of child-specific behavior.

Explore this amazing course and master all the key concepts of Java programming effortlessly!

Using Java extends With Interfaces (Default Methods)

In Java, interfaces allow you to define abstract behavior that classes can implement. Starting from Java 8, interfaces can also have default methods, which are methods with a default implementation. This allows you to provide common functionality across multiple classes without requiring them to implement the method themselves.

The extends keyword is used to allow one interface to inherit from another interface, and interfaces can also extend other interfaces. With default methods, interfaces can provide a default behavior, while still allowing implementing classes to override or extend that behavior.

Key Points To Remember:

  • Interfaces can inherit from other interfaces using extends.
  • Default methods allow interfaces to provide method implementations, which can be optionally overridden by classes.
  • Multiple interfaces can be extended, and default methods help avoid conflicts when the same method is defined in multiple interfaces.

Code Example: 

Output: 

The dog eats dog food.
This pet loves to play.

Explanation: 

In the above code example-

  1. We start with an interface Animal, which defines a default method eat(). This method outputs "This animal eats food." By using the default keyword, we allow the method to have a body, meaning it can be inherited by any class that implements this interface without needing to override it.
  2. We then define another interface Pet that extends the Animal interface using the extends keyword. This means that Pet inherits all methods from Animal, including the default eat() method. In addition, we add a new default method play() in the Pet interface, which outputs "This pet loves to play."
  3. Next, we create the Dog class that implements the Pet interface. By implementing the Pet interface, Dog must either override the default methods from Pet (and Animal) or use them as they are.
  4. In the Dog class, we choose to override the eat() method. Thus eat() outputs "The dog eats dog food." This overrides the inherited eat() method from the Animal interface, providing specific behavior for the Dog class.
  5. The Dog class doesn't need to override the play() method from the Pet interface because it can use the default implementation provided by the Pet interface. The method outputs "This pet loves to play." If we wanted to, we could override this method in the Dog class to give it a specific implementation.
  6. In the Main class, we create an object myDog of type Dog, which allows us to call methods defined in the Dog class as well as those inherited from the interfaces.
  7. By calling myDog.eat(), we invoke the overridden version of eat() in the Dog class, which outputs "The dog eats dog food."
  8. By calling myDog.play(), we invoke the default play() method from the Pet interface, which outputs "This pet loves to play."

Overriding Using extends Keyword In Java

Method overriding is a feature in Java that allows a subclass to provide a specific implementation for a method that is already defined in its superclass. This is done using the extends keyword to create an inheritance relationship, allowing the subclass to "override" the inherited method.

When a subclass overrides a method, it provides a new version of the method that matches the method signature of the parent class. Overriding is an essential concept in polymorphism and allows the behavior of inherited methods to be customized.

Code Example: 

Output:

The animal makes a sound.
The dog barks.

Explanation: 

In the above code example-

  1. We start with a parent class Animal, which contains a method makeSound(). This method outputs "The animal makes a sound." It represents a general behavior for animals in the Animal class.
  2. We then create a child class Dog, which extends the Animal class using the extends keyword. This establishes an inheritance relationship where the Dog class inherits the makeSound() method from Animal.
  3. In the Dog class, we override the makeSound() method to provide a specific implementation for dogs. The overridden method outputs "The dog barks," which is more appropriate for a dog compared to the general message in the Animal class.
  4. In the Main class, we create two objects: myAnimal of type Animal and myDog of type Dog.
  5. When we call myAnimal.makeSound(), the program uses the method from the Animal class, which outputs "The animal makes a sound."
  6. When we call myDog.makeSound(), the program uses the overridden method from the Dog class, which outputs "The dog barks." This demonstrates how a subclass can modify or specialize the behavior inherited from the superclass.

Sharpen your coding skills with Unstop's 100-Day Coding Sprint and compete now for a top spot on the leaderboard!

Difference Between extends And implements In Java

Both extends and implements are used to create relationships between classes and interfaces, but they serve different purposes and are applied in different contexts. Here are the key differences between the two: 

Aspect

Java extends

Java implements

Purpose

Used for inheritance — to establish a relationship between a class and another class or between an interface and another interface.

Used by a class to implement an interface, meaning the class agrees to provide concrete implementations for the abstract methods defined in the interface.

Used By

- A class can extend another class.

- An interface can extend another interface.

- A class implements one or more interfaces.

Multiple Inheritance

No (A class can only extend one class due to single inheritance).

Yes (A class can implement multiple interfaces, which allows multiple inheritance).

Inheritance Type

- Class to class: A subclass inherits fields and methods from its superclass.

- Interface to interface: An interface inherits method signatures from another interface.

A class must implement all methods declared in the interface.

Method Implementation

Inherits methods from the superclass. If the method is abstract in the superclass, the subclass must provide an implementation.

Must provide implementations for all abstract methods defined in the interface.

Fields Inherited

A class inherits fields (variables) from its superclass. The subclass can access them if they are public or protected.

A class does not inherit fields from an interface. It only implements the method signatures defined in the interface.

Constructor Inheritance

A subclass can inherit constructors from its superclass (indirectly, using super).

No constructors are inherited. A class implementing an interface does not inherit constructors from the interface.

Abstract Methods

- A subclass inherits abstract methods if the superclass has abstract methods.

- The subclass must provide an implementation (unless the subclass is also abstract).

A class must provide concrete implementations for all abstract methods of the interface.

Access Modifiers for Methods

A subclass can override the methods of its superclass, but the access modifier of the overridden method cannot be more restrictive than the method in the superclass.

A class implementing an interface can implement the interface's methods with any access modifier, but it must provide implementations for all abstract methods.

Class vs Interface Relationship

Establishes a relationship between a class and its superclass (or subclass).

Establishes a relationship between a class and an interface.

Type of Inheritance

Single inheritance for classes, but multiple inheritance for interfaces.

Multiple inheritance (A class can implement multiple interfaces).

Example

class Animal { }
class Dog extends Animal { }

interface Animal {
    void eat();
}

class Dog implements Animal {
    public void eat() { }
}



Abstract Methods in Superclass/Interface

If the superclass has abstract methods, the subclass must implement them.

A class must implement all abstract methods of an interface.

Default Methods

Not applicable. A class extending another class cannot directly inherit default methods.

An interface can have default methods with implementations, and classes implementing the interface can inherit them.

Supports Method Overriding

A subclass can override methods from the superclass.

A class can override methods from an interface (implementations of the interface's methods).

Real-World Analogy

Like a child inheriting traits (behavior) from their parents.

Like a worker following the rules set by an organization (the interface), but also bringing their own work skills (method implementations).

Therefore: 

  • Java extends is used to create a subclass from a superclass (inheritance), where the subclass inherits both fields and methods from the superclass.
  • Java implements is used when a class adopts the behavior of an interface and provides concrete implementations for its abstract methods.

​​Are you looking for someone to answer all your programming-related queries? Let's find the perfect mentor here.

Real World Applications Of Extends Keyword In Java

Below are some real-world scenarios where the extends keyword is commonly used in Java language:

1. Building a Hierarchical System (Employee Management System)

In an Employee Management System, we might have a general class Employee that is extended by more specialized classes like Manager, Developer, and Intern. The Manager class might have extra functionality, like the ability to assign tasks, while the Developer and Intern classes have different specific methods. For Example-

// Base Class
class Employee {
    void work() {
        System.out.println("Employee is working.");
    }
}

// Derived Class
class Manager extends Employee {
    void assignTask() {
        System.out.println("Manager is assigning tasks.");
    }
}

2. Vehicle Inheritance (Vehicle Management System)

In a Vehicle Management System, the extends keyword can model different types of vehicles like Car, Truck, and Motorcycle by creating a base class Vehicle and extending it for each type of vehicle. Each vehicle class may have specific methods related to its type. For Example-

// Base Class
class Vehicle {
    void start() {
        System.out.println("Vehicle is starting.");
    }
}

// Derived Class
class Car extends Vehicle {
    void honk() {
        System.out.println("Car is honking.");
    }
}

3. Banking System (Account Types)

In a Banking System, we can use inheritance to define various account types like SavingsAccount, CheckingAccount, or BusinessAccount. These subclasses can extend a base class BankAccount that holds common properties and methods for all account types. For Example-

// Base Class
class BankAccount {
    void deposit(double amount) {
        System.out.println("Depositing: " + amount);
    }
}

// Derived Class
class SavingsAccount extends BankAccount {
    void applyInterest() {
        System.out.println("Applying interest to savings account.");
    }
}

4. E-commerce System (Product Categories)

In an E-commerce System, different product categories can extend a base class Product. For example, Electronics, Clothing, and Books can be subclasses that have specific details, like warranty for electronics or size for clothing. For Example-

// Base Class
class Product {
    void displayProductInfo() {
        System.out.println("Product information.");
    }
}

// Derived Class
class Electronics extends Product {
    void displayWarranty() {
        System.out.println("Displaying warranty details.");
    }
}

5. Game Development (Character Types)

In Game Development, we often need to model different types of characters, such as Warrior, Mage, and Archer, which all inherit from a common base class Character. Each class can have specific abilities or stats, but they all share common actions like attack() or move(). For Example-

// Base Class
class Character {
    void move() {
        System.out.println("Character is moving.");
    }
}

// Derived Class
class Warrior extends Character {
    void useSword() {
        System.out.println("Warrior is using a sword.");
    }
}

Conclusion 

The extends keyword in Java is a powerful tool that enables classes to inherit properties and methods from other classes, promoting code reuse and simplifying software design. Whether you're working with single or multilevel inheritance, abstract classes, or interfaces, extends plays a crucial role in building flexible and maintainable code. 

However, it's important to use it wisely, keeping in mind best practices like avoiding deep inheritance hierarchies and knowing when to prefer composition over inheritance. By understanding and applying the extends keyword effectively, you can enhance your object-oriented programming skills and create more efficient, scalable Java applications.

Frequently Asked Questions

Q. What does the extends keyword do in Java?

The extends keyword in Java is used to create a subclass (child class) from a superclass (parent class), enabling the subclass to inherit methods and fields from the superclass. It allows for code reuse, making it easier to create a new class that builds upon an existing class, while adding or overriding functionalities. For example, if you have a Vehicle class, you can create a Car class that extends Vehicle, inheriting its properties and methods.

Q. Can a class extend more than one class in Java?

No, Java does not support multiple inheritance for classes. A class can only extend one other class at a time. This means that a class can inherit from only one superclass. However, Java allows multiple inheritance through interfaces. A class can implement multiple interfaces, thus achieving some benefits of multiple inheritance, but with more flexibility and less ambiguity.

Q. How does the extends keyword work with abstract classes?

When a class extends an abstract class, it inherits the abstract class's fields and methods, but it must implement all of the abstract methods defined in the parent class (unless the subclass is also abstract). The subclass is required to provide concrete implementations for these abstract methods to become a fully functional class. This makes abstract classes useful for creating a blueprint that must be followed by subclasses.

Q. What is the difference between extends and implements in Java?

The difference between them is as follows: 

  • extends: Used when a class inherits from another class (either concrete or abstract). A class can only extend one class, and the subclass inherits the methods and fields of the superclass.
  • implements: Used when a class implements an interface. A class can implement multiple interfaces, and it must provide concrete implementations for all methods declared in the interface. Interfaces are used to define a contract that a class must fulfill, but they do not provide method implementations.

Q. Can a subclass call a constructor of the superclass using extends?

Yes, a subclass can call a constructor from its superclass using the super() keyword. This is particularly useful when the superclass has a parameterized constructor. If the superclass does not have a default constructor (i.e., no constructor with no parameters), the subclass must explicitly call one of the superclass's constructors using super(). If the superclass has a no-argument constructor, it is automatically called, unless another constructor is explicitly invoked in the subclass.

Q. What happens if a subclass does not override a method from the superclass?

If a subclass does not override a method from the superclass, the subclass inherits the method as it is from the superclass. This means that the subclass will use the version of the method provided by the superclass, unless it needs to be customized by overriding it. If a method is not overridden and it is called on an object of the subclass, the superclass's version of the method will be executed.

With this, we conclude our discussion on the extends keyword in Java. Here are a few other topics that you might be interested in reading: 

  1. Convert String To Date In Java | 3 Different Ways With Examples
  2. Final, Finally & Finalize In Java | 15+ Differences With Examples
  3. Throws Keyword In Java | Syntax, Working, Uses & More (+Examples)
  4. How To Find LCM Of Two Numbers In Java? Simplified With Examples
  5. How To Find GCD Of Two Numbers In Java? All Methods With Examples
  6. Volatile Keyword In Java | Syntax, Working, Uses & More (+Examples)
Muskaan Mishra
Technical Content Editor

I’m a Computer Science graduate with a knack for creative ventures. Through content at Unstop, I am trying to simplify complex tech concepts and make them fun. When I’m not decoding tech jargon, you’ll find me indulging in great food and then burning it out at the gym.

TAGS
Java Programming Language
Updated On: 2 Dec'24, 03:57 PM IST