Extends in Java Tutorial

In this section, we will learn what the extends keyword is and how it works in Java.

Note: we’re assuming you’re already familiar with Java inheritance in general.

What Is Extends Keyword in Java?

The `extends` keyword is used to make a class inherit from another one and hence be able to use its members.

Java extends Keyword Syntax:

class ChildClass extends ParentClass{/*...*/}

The extends keyword comes after the child class name and after that comes the name of the class we want the child class to inherit from.

Example: extending a class in Java

package com.example.demo;

public class Child extends Parent{
    public void sayHiChild(){
        System.out.println("The child is saying Hi :)");
    }
}

Here, the Child class extended to the Parent class and hence, an instance of this class is able to use the public members of the `Parent` class as well.

Java extends vs implements

There’s another keyword in Java called `implements`. The main difference between the `extends` and the `implements` is that the second one is used when we want a class to use one or more Java interfaces, while the first one is used when we want a class to inherit from another class.

Note: you’ll learn more about this `implements` keyword in the interface section.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies