Java Extends Keyword

Java Extends Keyword


Extends Keyword In Java
We use extends keyword in inheritance in Java.
Java supports inheritance by allowing one class to incorporate another class into its declaration. This is done by using the extends keyword.
Thus, the subclass adds to (extends) the superclass. In other words, To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword.
Note -
In the language of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the variables and methods defined by the superclass and adds its own, unique elements. 
We use extends keyword to inherit from one class to another class.
Syntax -
class subclassName extends superclassName { // body of class
}

 
Now we will see the usage of extends keyword with the help of an example- 
Example- The following program creates a superclass called A and a subclass called B. Notice how the keyword extends is used to create a subclass of A.
package javaLearnings;
// A simple example of inheritance.
// Create a superclass.
class A {
  int i, j;
  void showij() {
      System.out.println("i and j: " + i + " " + j);
  }
}
// Create a subclass by extending class A.
class B extends A {
  int k;
  void showk() {
      System.out.println("k: " + k);
  }
  void sum() {
      System.out.println("i+j+k: " + (i+j+k));
  }
}
public class Main {

  public static void main(String[] args) {
  // write your code here
      A superOb = new A();
      B subOb = new B();
// The superclass may be used by itself.
      superOb.i = 10;
      superOb.j = 20;
      System.out.println("Contents of superOb: ");
      superOb.showij();
      System.out.println();
/* The subclass has access to all public members of
its superclass. */
      subOb.i = 7;
      subOb.j = 8;
      subOb.k = 9;
      System.out.println("Contents of subOb: ");
      subOb.showij();
      subOb.showk();
      System.out.println();
      System.out.println("Sum of i, j and k in subOb:");
      subOb.sum();

  }

}

 
Output -
Contents of superOb:

i and j: 10 20

Contents of subOb: i and j: 7 8

k: 9

Sum of i, j and k in subOb:

i+j+k: 24

 
As you can see, subclass B includes all of the members of its superclass, A. This is why subOb can access i and j and call showij( ). Also, inside sum( ), i, and j can be referred to directly, as if they were part of B.